-
Notifications
You must be signed in to change notification settings - Fork 0
/
useDataStore.js
78 lines (68 loc) · 2 KB
/
useDataStore.js
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
import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setDataStoreItem } from '../redux-store';
import { API } from '../api';
/**
* useDataStore() Hook
*
* Fetch, cache, and fetch cached API data.
*
* @returns {object} The data store object.
*/
function useDataStore() {
const dispatch = useDispatch();
const dataStore = useSelector(state => state.dataStore);
/**
* Set
*/
const set = useCallback((key, value) => {
dispatch(setDataStoreItem({
key,
value
}));
}, [dispatch]);
/**
* Get
*
* @param {string} key
* @param {object} config
*/
const get = useCallback((key, config = {}) => {
return new Promise((resolve, reject) => {
/**
* Configuration
*
* @property {bool} useCache
*/
const {
useCache = false
} = config;
// return data from redux store / cache if requested and available
if (useCache && dataStore[key] !== undefined) {
resolve(dataStore[key]);
}
// fetch data from API if cache not requested
API.get(key)
.then(response => {
// successful API requests should always return an
// object with a "data" attribute
if (response.data !== undefined) {
// update the redux store / cache
set(key, response.data);
// return the data
resolve(response.data);
}
// treat the lack of "data" attribute as an empty response
resolve(null);
})
.catch(error => {
reject(error);
});
});
}, [dataStore, set]);
return {
get,
set
};
}
export default useDataStore;