forked from reactplay/react-play
-
Notifications
You must be signed in to change notification settings - Fork 0
/
usePlayFilter.js
53 lines (43 loc) · 1.67 KB
/
usePlayFilter.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
// THIS HOOKS GRABS ALL THE FILTERABLE DATA FOR THE MODAL
import { fetchFilterData } from 'common/services/request/query/fetch-filter-data';
import { submit_multi } from '../../services/request';
import { useEffect, useState } from 'react';
import { getAllTags as extractTags } from 'meta/play-meta-util';
import useCacheResponse from 'common/hooks/useCacheResponse';
/**
* run graphql query to retrive filterable data like creators, tags, level
* @returns [loading, error, data]
*/
const FILTER_DATA_RESPONSE = 'FILTER_DATA_RESPONSE';
const useFetchFilterData = () => {
const { getAllTags, getAllLevels, getAllUsers } = fetchFilterData;
const [getCacheResponse, setCacheResponse] = useCacheResponse();
const [loading, setLoading] = useState(false);
const [data, setData] = useState({});
const [error, setError] = useState(null);
const dataConstructor = (data) => {
const [tags, levels, creators] = data;
const structuredTags = extractTags(tags);
return { tags: structuredTags, levels, creators };
};
useEffect(() => {
(async () => {
try {
setLoading(true);
const isCachedResponse = getCacheResponse(FILTER_DATA_RESPONSE);
if (isCachedResponse) {
return setData(dataConstructor(isCachedResponse));
}
const response = await submit_multi([getAllTags, getAllLevels, getAllUsers]);
setCacheResponse(FILTER_DATA_RESPONSE, response);
setData(dataConstructor(response));
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}, [getAllTags, getAllLevels, getAllUsers]);
return [loading, error, data];
};
export default useFetchFilterData;