Skip to content

Commit

Permalink
cached data internally in order to prevent multiple api calls on each…
Browse files Browse the repository at this point in the history
… filter modal mount (reactplay#875)

* cached data internally in order to prevent multiple api calls on each filter modal mount

* eslint fix

Co-authored-by: Tapas Adhikary <[email protected]>
  • Loading branch information
Angryman18 and atapas committed Jan 18, 2023
1 parent d415477 commit d030232
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/common/hooks/useCacheResponse.ts
Original file line number Diff line number Diff line change
@@ -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;
9 changes: 9 additions & 0 deletions src/common/search/hooks/usePlayFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({});
Expand All @@ -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);
Expand Down

0 comments on commit d030232

Please sign in to comment.