|
1 | | -import React from 'react' |
| 1 | +import React, { ReactElement, ReactNode } from 'react' |
2 | 2 | import { isFunction } from '../util' |
3 | 3 |
|
4 | | -type LoadingFunction = () => React.ReactElement<any, any> | null |
5 | | -type SuccessFunction<Data> = (data: Data) => React.ReactElement<any, any> | null |
6 | | -type ErrorFunction<Error> = ( |
7 | | - error: Error |
8 | | -) => React.ReactElement<any, any> | null |
| 4 | +type LoadingFunction = () => ReactNode |
| 5 | +type SuccessFunction<Data> = (data: NonNullable<Data>) => ReactNode |
| 6 | +type ErrorFunction<Error> = (error: NonNullable<Error>) => ReactNode |
9 | 7 |
|
10 | 8 | type Props<Data, Error> = { |
11 | 9 | data?: Data |
12 | 10 | error?: Error |
13 | | - renderLoading?: React.ReactNode | LoadingFunction |
14 | | - renderSuccess: React.ReactNode | SuccessFunction<Data> |
15 | | - renderError?: React.ReactNode | ErrorFunction<Error> |
| 11 | + renderLoading?: ReactNode | LoadingFunction |
| 12 | + renderSuccess: ReactNode | SuccessFunction<Data> |
| 13 | + renderError?: ReactNode | ErrorFunction<Error> |
16 | 14 | } |
17 | 15 |
|
18 | 16 | const AsyncView = <Data, Error>( |
19 | 17 | props: Props<Data, Error> |
20 | | -): React.ReactElement<any, any> | null => { |
| 18 | + // The `ReactElement<any, any> | null` type is for React 17 compatibility (see type FunctionComponent). With React 18 it can be a ReactNode and we can remove the Fragment wrappers. |
| 19 | +): ReactElement<any, any> | null => { |
21 | 20 | const { |
22 | 21 | data, |
23 | 22 | error, |
24 | 23 | renderLoading = null, |
25 | 24 | renderSuccess, |
26 | 25 | renderError = null, |
27 | 26 | } = props |
28 | | - if (error != null && error != undefined) { |
29 | | - return isFunction(renderError) ? renderError(error) : <>{renderError}</> |
30 | | - } else if (data != null && data != undefined) { |
31 | | - return isFunction(renderSuccess) ? ( |
32 | | - renderSuccess(data) |
33 | | - ) : ( |
34 | | - <>{renderSuccess}</> |
| 27 | + if (error !== null && error !== undefined) { |
| 28 | + return <>{isFunction(renderError) ? renderError(error) : renderError}</> |
| 29 | + } else if (data !== null && data !== undefined) { |
| 30 | + return ( |
| 31 | + <>{isFunction(renderSuccess) ? renderSuccess(data) : renderSuccess}</> |
35 | 32 | ) |
36 | 33 | } else { |
37 | | - return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</> |
| 34 | + return <>{isFunction(renderLoading) ? renderLoading() : renderLoading}</> |
38 | 35 | } |
39 | 36 | } |
40 | 37 |
|
|
0 commit comments