Skip to main content

hook: useFetch with cache, and useReducer

 https://www.smashingmagazine.com/2020/07/custom-react-hook-fetch-cache-data/


import { useEffect, useRef, useReducer } from 'react';
export const useFetch = (url) => {
const cache = useRef({});
const initialState = {
status: 'idle',
error: null,
data: [],
};
const [state, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'FETCHING':
return { ...initialState, status: 'fetching' };
case 'FETCHED':
return { ...initialState, status: 'fetched', data: action.payload };
case 'FETCH_ERROR':
return { ...initialState, status: 'error', error: action.payload };
default:
return state;
}
}, initialState);
useEffect(() => {
let 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 response = await fetch(url);
const data = await response.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();
return function cleanup() {
cancelRequest = true;
};
}, [url]);
return state;
};

Comments

Popular posts from this blog

for loop in javascript - promise - .eslintrc for "for of"

the vast majority of cases  map ,  forEach ,  find  etc. can be used.  async function printFiles () { const files = await getFilePaths(); await Promise.all(files. map (async (file) => { const contents = await fs.readFile(file, 'utf8') console.log(contents) })); } const inventory = [ { name : 'apples' , quantity : 2 } , { name : 'bananas' , quantity : 0 } , { name : 'cherries' , quantity : 5 } ] ; const result = inventory . find ( ( { name } ) => name === 'cherries' ) ;   function getFirstMatching(array) { for (let item of array) { const result = heavyTransform(item); if (result) { return result; } } } Specifically this shuts down the whole no-restricted-syntax. If you want to cherry-pick, here is the current definition: 'no-restricted-syntax' : [ 'error' , { selector : 'ForInStatement' , message...

Apollo client - cache APIs - auto update cache - erase cache - reactive variables - deletion - addition

Apollo Client 3  Local only fields Reactive Variables const cache = new InMemoryCache ( { typePolicies : { Todo : { // If one of the keyFields is an object with fields of its own, you can // include those nested keyFields by using a nested array of strings: keyFields : [ "date" , "user" , [ "email" ] ] , } } , } ) ; This internal data is intended to be easily  JSON-serializable , so you can take a snapshot with  cache.extract() , save it somewhere, and later restore with  cache.restore(snapshot) . Here’s a mutation called  EditTodo  that returns the new  todo  value in the mutation response. mutation EditTodo ( $id : Int ! , $text : String ! ) { editTodo ( id : $id , text : $text ) { success todo { # <- Returning it here id text completed } error { ... on TodoNotFoundError { message } ... on TodoValidationE...

window.URL.createObjectURL is not (yet) available in jest-dom - testing scenario

Since  window.URL.createObjectURL  is not (yet) available in jest-dom, you need to provide a mock implementation for it. Don't forget to reset the mock implementation after each test. describe ( "your test suite" , () => { window . URL . createObjectURL = jest . fn (); afterEach (() => { window . URL . createObjectURL . mockReset (); }); it ( "your test case" , () => { expect ( true ). toBeTruthy (); }); });