-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoadingSwitch.js
More file actions
72 lines (60 loc) · 1.71 KB
/
Copy pathLoadingSwitch.js
File metadata and controls
72 lines (60 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// @flow
import { Component, type Node } from 'react'
import isPending, { type PendingValue } from './utils/isPending'
/*
LoadingSwitch
-------------
A switcher based on the presence of data and apollo loading information.
Note: This component is generic enough that it should be its own package shared
between our mobile and web apps, and also really any app that uses react-apollo
@example
render() {
const { loading, error, media, artist } = this.props.data
<LoadingSwitch
error={error}
errorWhenMissing={() => new Error('Missing required data!')}
loading={loading}
renderError={(error) => <DataError error={error} />}
renderLoading={() => <Loading />}
require={media && artist}
>
{ () => (
<Text>This is rendered when have the data! { media.id }</Text>
) }
</LoadingSwitch>
}
*/
export type Props = {|
children: ?Node | ?() => ?Node,
error: ?Error,
errorWhenMissing: Error | () => Error,
loading: boolean,
renderError: (Error) => ?Node,
renderLoading: () => ?Node,
require: PendingValue,
|}
class LoadingSwitch extends Component<Props> {
render() {
const {
children,
error,
errorWhenMissing,
loading,
renderError,
renderLoading,
require,
} = this.props
if (error) {
return renderError(error)
}
if (isPending(require)) {
if (loading) {
return renderLoading()
}
return renderError(errorWhenMissing && typeof errorWhenMissing === 'function' ? errorWhenMissing() : errorWhenMissing)
}
return children && typeof children === 'function' ? children() : children
}
}
LoadingSwitch.displayName = 'LoadingSwitch'
module.exports = LoadingSwitch