Skip to content

Instantly share code, notes, and snippets.

@rohitsSpace
Last active October 26, 2021 21:12
Show Gist options
  • Save rohitsSpace/d95aba8447c7cabbd507c69ce1196f2e to your computer and use it in GitHub Desktop.
Save rohitsSpace/d95aba8447c7cabbd507c69ce1196f2e to your computer and use it in GitHub Desktop.
In memory Cacheable Fetch API react hook
import { useEffect, useRef, useReducer } from 'react';
export const useCacheAbleFetch = (url) => {
const cache = useRef({});
const initialState = {
status: 'idle',
error: null,
data: [],
loading: false, // helper to get loading state of the request
};
const [state, dispatch] = useReducer((newState, action) => {
switch (action.type) {
case 'FETCHING':
return { ...initialState, status: 'fetching', loading: true };
case 'FETCHED':
return {
...initialState, status: 'fetched', data: action.payload.data.data, loading: false,
};
case 'FETCH_ERROR':
return { ...initialState, status: 'error', error: action.payload };
default:
return newState;
}
}, initialState);
useEffect(() => {
const cancelRequest = false;
if (!url) return;
const fetchData = async () => {
dispatch({ type: 'FETCHING' });
if (cache.current[url]) {
const data = cache.current[url];
dispatch({ type: 'FETCHED', payload: data });
} else {
try {
const res = await fetch(url);
const data = await res.json();
cache.current[url] = data;
if (cancelRequest) return;
dispatch({ type: 'FETCHED', payload: data });
} catch (error) {
if (cancelRequest) return;
dispatch({ type: 'FETCH_ERROR', payload: error.message });
}
}
};
fetchData();
}, [url]);
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment