Skip to content

Commit a668fd2

Browse files
authored
add fallback behaviour for is-loading (#20)
* add fallback behaviour for is-loading, if set to undefined * make data, error and is-loading required but undefindable
1 parent d13a0dc commit a668fd2

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/async-data/AsyncView.tsx

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

44
type LoadingFunction = () => ReactNode
55
type SuccessFunction<Data> = (data: Data) => ReactNode
66
type ErrorFunction<Error> = (error: NonNullable<Error>) => ReactNode
77

88
type Props<Data, Error> = {
9-
data?: Data
10-
error?: Error
11-
isLoading: boolean
9+
/**
10+
* The async data to show.
11+
* Note that `error` and `isLoading` take precedence over data.
12+
*/
13+
data: Data | undefined
14+
/**
15+
* Set an error to show the error state.
16+
* Note that `isLoading` takes precedence over error.
17+
*/
18+
error: Error | undefined
19+
/**
20+
* Set to a boolean value to explicitly control loading state.
21+
* If undefined, loading state is shown when there is no data (null | undefined) and no error (null | undefined).
22+
*/
23+
isLoading: boolean | undefined
1224
renderLoading?: ReactNode | LoadingFunction
1325
renderError?: ReactNode | ErrorFunction<Error>
1426
} & (
@@ -36,15 +48,18 @@ const AsyncView = <Data, Error>(
3648
allowMissingData = false,
3749
} = props
3850

39-
if (isLoading) {
51+
const isError = error !== null && error !== undefined
52+
const hasData = data !== null && data !== undefined
53+
54+
if (isLoading || (isLoading === undefined && !hasData && !isError)) {
4055
return <>{isFunction(renderLoading) ? renderLoading() : renderLoading}</>
4156
}
4257

43-
if (error !== null && error !== undefined) {
58+
if (isError) {
4459
return <>{isFunction(renderError) ? renderError(error) : renderError}</>
4560
}
4661

47-
if ((data === undefined || data === null) && !allowMissingData) {
62+
if (!hasData && !allowMissingData) {
4863
throw new Error(
4964
'Data passed into AsyncView was null or undefined. Use allowMissingData=true if this is intended.',
5065
)

0 commit comments

Comments
 (0)