-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.jsx
103 lines (77 loc) · 2.31 KB
/
index.jsx
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { useState, createContext, useContext, useCallback } from "react"
export const CacheContext = createContext({ getCache: () => null, setCache: () => {}, store: {} })
export const CacheProvider = ({ children }) => {
const [store, setStore] = useState({})
const getCache = (key) => {
return store[key]
}
const setCache = (key, value) => {
setStore((store) => ({
...store,
[key]: value,
}))
}
return (
<CacheContext.Provider value={{ getCache, setCache, store }}>
{children}
</CacheContext.Provider>
)
}
const BasePathContext = createContext()
export const BasePathProvider = ({ value, children }) => {
return <BasePathContext.Provider value={value}>{children}</BasePathContext.Provider>
}
export const useResource = (path, { root } = {}) => {
const basePath = useContext(BasePathContext)
const { getCache, setCache } = useContext(CacheContext)
const [fetching, setFetching] = useState(false)
const [updating, setUpdating] = useState(false)
const [destroying, setDestroying] = useState(false)
const fullPath = basePath ? basePath + path : path
const resource = getCache(fullPath)
const fetchResource = useCallback(async () => {
setFetching(true)
const response = await fetch(fullPath)
const data = await response.json()
if (root) {
setCache(fullPath, data[root])
}
else {
setCache(fullPath, data)
}
setFetching(false)
}, [])
const updateResource = (id, attributes) => {}
const destroyResource = (id) => {}
return [
resource,
{
fetchResource,
updateResource,
destroyResource,
fetching,
updating,
destroying
},
]
}
export const useCollection = (path, { root } = {}) => {
const basePath = useContext(BasePathContext)
const { getCache, setCache } = useContext(CacheContext)
const [fetching, setFetching] = useState(false)
const fullPath = basePath ? basePath + path : path
const collection = getCache(fullPath)
const fetchCollection = useCallback(async () => {
setFetching(true)
const response = await fetch(fullPath)
const data = await response.json()
if (root) {
setCache(fullPath, data[root])
}
else {
setCache(fullPath, data)
}
setFetching(false)
}, [])
return [collection, { fetchCollection, fetching }]
}