Skip to content

Instantly share code, notes, and snippets.

@manandearth
Created November 1, 2019 20:46
Show Gist options
  • Save manandearth/917498368d456ab2658d7433fb625e6e to your computer and use it in GitHub Desktop.
Save manandearth/917498368d456ab2658d7433fb625e6e to your computer and use it in GitHub Desktop.
mocking a react hook
I'll start at the highest level and go in.
the relevant part of the react component that calls the custom hook:
//////////////
//product.js//
//////////////
///////////////////////////
//useProductDetailData.js//
///////////////////////////
import React, {
Fragment,
useState,
useEffect,
useReducer,
} from 'react';
import axios from 'axios';
import useGlobal from '../../store/store'
/**
* Custom hook to get data from endpoints.
* @param state
* @param action
* @returns {{isLoading: boolean, isError: boolean, data: *}|{isLoading: boolean, isError: boolean}}
*/
const dataFetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return {
...state,
isLoading: true,
isError: false,
isExpired: false,
};
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
isExpired: false,
data: action.payload,
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true,
isExpired: false,
};
case 'FETCH_EXPIRED':
return {
...state,
isLoading: false,
isError: false,
isExpired: true,
};
default:
throw new Error();
}
};
const useProductDetailData = (initialUrl, initialData) => {
const [globalState, globalActions] = useGlobal();
const [url, setUrl] = useState(initialUrl);
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
isExpired: false,
data: initialData,
});
useEffect(() => {
let didCancel = false;
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' });
try {
const result = await axios(
url,
{
'headers': {
"Accept": "application/json",
'Authorization': "Bearer " + globalState.token,
}
});
if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
}
} catch (error) {
if (!didCancel) {
if (
error && error.response && error.response.status === 401
){
dispatch({type: 'FETCH_EXPIRED'})
} else {
dispatch({ type: 'FETCH_FAILURE' });
}
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [globalState.token, url]);
return [state, setUrl];
};
export default useProductDetailData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment