|
| 1 | + |
| 2 | +import { Component, type Node } from 'react' |
| 3 | + |
| 4 | +/* |
| 5 | +LoadingSwitch |
| 6 | +------------- |
| 7 | +
|
| 8 | +A switcher based on the presence of data and apollo loading information. |
| 9 | +
|
| 10 | +Note: This component is generic enough that it should be its own package shared |
| 11 | +between our mobile and web apps, and also really any app that uses react-apollo |
| 12 | +
|
| 13 | +@example |
| 14 | + render() { |
| 15 | + const { loading, error, media, artist } = this.props.data |
| 16 | +
|
| 17 | + <LoadingSwitch |
| 18 | + error={error} |
| 19 | + errorWhenMissing={() => new Error('Missing required data!')} |
| 20 | + loading={loading} |
| 21 | + renderError={(error) => <DataError error={error} />} |
| 22 | + renderLoading={() => <Loading />} |
| 23 | + require={media && artist} |
| 24 | + > |
| 25 | + { () => ( |
| 26 | + <Text>This is rendered when have the data! { media.id }</Text> |
| 27 | + ) } |
| 28 | + </LoadingSwitch> |
| 29 | + } |
| 30 | +
|
| 31 | +*/ |
| 32 | + |
| 33 | +export type PendingValue = any |
| 34 | + |
| 35 | +// TODO: Import |
| 36 | +// Isolated in case we want to modify this behavior in the future. |
| 37 | +export const isPending: (PendingValue) => boolean = (pendingValue) => !pendingValue |
| 38 | + |
| 39 | +export type Props = {| |
| 40 | + children: ?Node | ?() => ?Node, |
| 41 | + error: ?Error, |
| 42 | + errorWhenMissing: Error | () => Error, |
| 43 | + loading: boolean, |
| 44 | + renderError: (Error) => ?Node, |
| 45 | + renderLoading: () => ?Node, |
| 46 | + require: PendingValue, |
| 47 | +|} |
| 48 | + |
| 49 | +class LoadingSwitch extends Component<Props> { |
| 50 | + static displayName = 'LoadingSwitch' |
| 51 | + |
| 52 | + render = () => { |
| 53 | + let { |
| 54 | + children, |
| 55 | + error, |
| 56 | + errorWhenMissing, |
| 57 | + loading, |
| 58 | + renderError, |
| 59 | + renderLoading, |
| 60 | + require, |
| 61 | + } = this.props |
| 62 | + |
| 63 | + if (error) { |
| 64 | + return renderError(error) |
| 65 | + } |
| 66 | + |
| 67 | + if (isPending(require)) { |
| 68 | + if (loading) { |
| 69 | + return renderLoading() |
| 70 | + } |
| 71 | + |
| 72 | + return renderError(errorWhenMissing && typeof errorWhenMissing === 'function' ? errorWhenMissing() : errorWhenMissing) |
| 73 | + } |
| 74 | + |
| 75 | + return children && typeof children === 'function' ? children() : children |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +export default LoadingSwitch |
0 commit comments