Skip to main content

Posts

Showing posts from February, 2021

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 ( ) => { ...