Last active
October 1, 2019 06:32
-
-
Save adeelibr/0158c61b82b5872f3609f9df38758099 to your computer and use it in GitHub Desktop.
A "hacky" approach to use instead of AbortControllers
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
/** | |
* @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