-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathCachedDataQueryProvider.js
More file actions
56 lines (47 loc) · 1.52 KB
/
CachedDataQueryProvider.js
File metadata and controls
56 lines (47 loc) · 1.52 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
import { useDataQuery } from '@dhis2/app-runtime'
import { Layer, CenteredContent, CircularLoader, NoticeBox } from '@dhis2/ui'
import PropTypes from 'prop-types'
import React, { createContext, useContext } from 'react'
import i18n from '../locales/index.js'
const CachedDataQueryCtx = createContext({})
const CachedDataQueryProvider = ({
query,
dataTransformation,
children,
translucent = true,
}) => {
const { data: rawData, ...rest } = useDataQuery(query)
const { error, loading } = rest
const data =
rawData && dataTransformation ? dataTransformation(rawData) : rawData
if (loading) {
return (
<Layer translucent={translucent}>
<CenteredContent>
<CircularLoader />
</CenteredContent>
</Layer>
)
}
if (error) {
const fallbackMsg = i18n.t('This app could not retrieve required data.')
return (
<NoticeBox error title={i18n.t('Network error')}>
{error.message || fallbackMsg}
</NoticeBox>
)
}
return (
<CachedDataQueryCtx.Provider value={data}>
{children}
</CachedDataQueryCtx.Provider>
)
}
CachedDataQueryProvider.propTypes = {
children: PropTypes.node.isRequired,
query: PropTypes.object.isRequired,
dataTransformation: PropTypes.func,
translucent: PropTypes.bool,
}
const useCachedDataQuery = () => useContext(CachedDataQueryCtx)
export { CachedDataQueryProvider, useCachedDataQuery }