Created
June 3, 2019 22:03
-
-
Save StarpTech/58509c503e89e0b9f69add3987c3b308 to your computer and use it in GitHub Desktop.
React Hooks Axios Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by https://www.robinwieruch.de/react-hooks-fetch-data/ | |
const dataFetchReducer = (state, action) => { | |
switch (action.type) { | |
case 'REQUEST_INIT': | |
return { ...state, isLoading: true, isError: false }; | |
case 'REQUEST_SUCCESS': | |
return { ...state, isLoading: false, isError: false, data: action.payload }; | |
case 'REQUEST_FAILURE': | |
return { ...state, isLoading: false, isError: true }; | |
default: | |
throw new Error(); | |
} | |
}; | |
export const useApiClient = (initialRequest = null, initialData = null, onFirstRun = false) => { | |
const [request, setRequest] = useState(initialRequest); | |
const [state, dispatch] = useReducer(dataFetchReducer, { | |
isLoading: false, | |
isError: false, | |
data: initialData | |
}); | |
// refs will persist for the full lifetime of the component. | |
const isFirstRun = useRef(!onFirstRun); | |
useEffect(() => { | |
const axiosCancelSource = axios.CancelToken.source(); | |
const getData = async () => { | |
if (isFirstRun.current) { | |
isFirstRun.current = false; | |
return; | |
} | |
dispatch({ type: 'REQUEST_INIT' }); | |
try { | |
request.cancelToken = axiosCancelSource.token; | |
const data = await axios(request); | |
dispatch({ type: 'REQUEST_SUCCESS', payload: data }); | |
} catch (error) { | |
dispatch({ type: 'REQUEST_FAILURE' }); | |
if (axios.isCancel(error)) { | |
logger.info('Request canceled', error.message); | |
} else { | |
throw error; | |
} | |
} | |
}; | |
getData(); | |
return () => { | |
axiosCancelSource.cancel('Component unmounted.'); | |
}; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [request]); | |
return [state, setRequest]; | |
}; | |
const [state, getProduct] = useApiClient(); | |
getProduct({ | |
method: 'get', | |
url: '/api/products/1' | |
}) | |
state.data | |
state.isLoading | |
state.isError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment