diff --git a/src/common/hooks/useCacheResponse.ts b/src/common/hooks/useCacheResponse.ts new file mode 100644 index 000000000..de350ef8e --- /dev/null +++ b/src/common/hooks/useCacheResponse.ts @@ -0,0 +1,21 @@ +interface TcacheObject { + [key: string]: any; +} + +type TReturn = [(s: string) => any, (t: string, c: any) => void]; + +const cacheObject: TcacheObject = new Object(); + +const useCacheResponse = (): TReturn => { + const createCache = (cacheName: string, cacheData: any): any => { + cacheObject[cacheName] = cacheData; + }; + + const retrieveCache = (cacheName: string): any => { + return cacheObject[cacheName] ? cacheObject[cacheName] : null; + }; + + return [retrieveCache, createCache]; +}; + +export default useCacheResponse; diff --git a/src/common/search/hooks/usePlayFilter.js b/src/common/search/hooks/usePlayFilter.js index baba77a21..e3e03f948 100644 --- a/src/common/search/hooks/usePlayFilter.js +++ b/src/common/search/hooks/usePlayFilter.js @@ -4,14 +4,18 @@ 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({}); @@ -28,7 +32,12 @@ const useFetchFilterData = () => { (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);