Skip to content

Commit 411c7c8

Browse files
authored
improve types of async-view (#14)
* support react-node as return type for render functions * make data + error types non-nullable for async-view's render functions
1 parent 9d4b415 commit 411c7c8

1 file changed

Lines changed: 15 additions & 18 deletions

File tree

src/async-data/AsyncView.tsx

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,37 @@
1-
import React from 'react'
1+
import React, { ReactElement, ReactNode } from 'react'
22
import { isFunction } from '../util'
33

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
97

108
type Props<Data, Error> = {
119
data?: Data
1210
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>
1614
}
1715

1816
const AsyncView = <Data, Error>(
1917
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 => {
2120
const {
2221
data,
2322
error,
2423
renderLoading = null,
2524
renderSuccess,
2625
renderError = null,
2726
} = 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}</>
3532
)
3633
} else {
37-
return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</>
34+
return <>{isFunction(renderLoading) ? renderLoading() : renderLoading}</>
3835
}
3936
}
4037

0 commit comments

Comments
 (0)