Skip to content

Commit 2b62bbd

Browse files
committed
update AsyncView to work with swr's loading flag and support nullable data payloads
1 parent 4bb6ae7 commit 2b62bbd

1 file changed

Lines changed: 32 additions & 8 deletions

File tree

src/async-data/AsyncView.tsx

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,25 @@ import React, { ReactElement, ReactNode } from 'react'
22
import { isFunction } from '../util'
33

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

88
type Props<Data, Error> = {
99
data?: Data
1010
error?: Error
11+
isLoading: boolean
1112
renderLoading?: ReactNode | LoadingFunction
12-
renderSuccess: ReactNode | SuccessFunction<Data>
1313
renderError?: ReactNode | ErrorFunction<Error>
14-
}
14+
} & (
15+
| {
16+
allowMissingData: true
17+
renderSuccess: ReactNode | SuccessFunction<Data>
18+
}
19+
| {
20+
allowMissingData?: false
21+
renderSuccess: ReactNode | SuccessFunction<NonNullable<Data>>
22+
}
23+
)
1524

1625
const AsyncView = <Data, Error>(
1726
props: Props<Data, Error>,
@@ -20,19 +29,34 @@ const AsyncView = <Data, Error>(
2029
const {
2130
data,
2231
error,
32+
isLoading,
2333
renderLoading = null,
2434
renderSuccess,
2535
renderError = null,
36+
allowMissingData = false,
2637
} = props
38+
39+
if (isLoading) {
40+
return <>{isFunction(renderLoading) ? renderLoading() : renderLoading}</>
41+
}
42+
2743
if (error !== null && error !== undefined) {
2844
return <>{isFunction(renderError) ? renderError(error) : renderError}</>
29-
} else if (data !== null && data !== undefined) {
30-
return (
31-
<>{isFunction(renderSuccess) ? renderSuccess(data) : renderSuccess}</>
45+
}
46+
47+
if ((data === undefined || data === null) && !allowMissingData) {
48+
throw new Error(
49+
'Data passed into AsyncView was null or undefined. Use allowMissingData=true if this is intended.',
3250
)
33-
} else {
34-
return <>{isFunction(renderLoading) ? renderLoading() : renderLoading}</>
3551
}
52+
53+
return (
54+
<>
55+
{isFunction(renderSuccess)
56+
? renderSuccess(data as NonNullable<Data>)
57+
: renderSuccess}
58+
</>
59+
)
3660
}
3761

3862
export { AsyncView }

0 commit comments

Comments
 (0)