Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Created June 3, 2019 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StarpTech/58509c503e89e0b9f69add3987c3b308 to your computer and use it in GitHub Desktop.
Save StarpTech/58509c503e89e0b9f69add3987c3b308 to your computer and use it in GitHub Desktop.
React Hooks Axios Client
// 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