Skip to content

Instantly share code, notes, and snippets.

@adeelibr
Last active October 1, 2019 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adeelibr/0158c61b82b5872f3609f9df38758099 to your computer and use it in GitHub Desktop.
Save adeelibr/0158c61b82b5872f3609f9df38758099 to your computer and use it in GitHub Desktop.
A "hacky" approach to use instead of AbortControllers
/**
* @description Hacky implementation for ignoring
* @param {Function} callback
* @param {Array of primitive dependencies} deps, because
* Arrays & Objects don't work in useEffect deps
*/
const useIgnore = (callback, deps) => {
const [{success, error, loading}, setState] = React.useState({
success: null,
error: null,
loading: null,
});
React.useEffect(async () => {
let ignore = true;
try {
setState(state => ({ ...state, loading: !state.loading }));
const response = await callback();
if (!ignore) {
setState(state => ({ loading: !state.loading, success: response, error: null }))
}
} catch (err) {
if (!ignore) {
setState(state => ({ loading: !state.loading, success: null, error: err }))
}
}
return () => {
ignore = false;
}
}, [...deps]);
return { success, error, loading };
}
const Example = ({ pageNo = 0, limit = 20 }) => {
const fetchMock = async () => {
return new Promise.resolve(100);
}
/**
* success: will have the API 200 respone
* error: will have the 400/500 response
* loading: will show the status of API loading.
*/
const { success, error, loading } = useIgnore(fetchMock, [pageNo, limit]);
// then do whatever you want with the response.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment