Created
July 23, 2019 05:59
-
-
Save Yang03/5d3de65a5746646058dd7aa0cc3148b7 to your computer and use it in GitHub Desktop.
Abort Data Fetching in Effect HooK
This file contains hidden or 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
const useDataApi = (initialUrl, initialData) => { | |
const [url, setUrl] = useState(initialUrl); | |
const [state, dispatch] = useReducer(dataFetchReducer, { | |
isLoading: false, | |
isError: false, | |
data: initialData, | |
}); | |
useEffect(() => { | |
let didCancel = false; | |
const fetchData = async () => { | |
dispatch({ type: 'FETCH_INIT' }); | |
try { | |
const result = await axios(url); | |
if (!didCancel) { | |
dispatch({ type: 'FETCH_SUCCESS', payload: result.data }); | |
} | |
} catch (error) { | |
if (!didCancel) { | |
dispatch({ type: 'FETCH_FAILURE' }); | |
} | |
} | |
}; | |
fetchData(); | |
return () => { | |
didCancel = true; | |
}; | |
}, [url]); | |
return [state, setUrl]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[{isLoading, isError, data}, doFetch] = useDataApi(url, null)