Skip to content

Commit 2a7516f

Browse files
committed
abort setting state when component got unmounted
1 parent 4d3bb1c commit 2a7516f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/useDataApiHook-example/index.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,29 @@ const useDataApi = (initialUrl, initialData) => {
3939
});
4040

4141
useEffect(() => {
42+
let didCancel = false;
43+
4244
const fetchData = async () => {
4345
dispatch({ type: 'FETCH_INIT' });
4446

4547
try {
4648
const result = await axios(url);
4749

48-
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
50+
if (!didCancel) {
51+
dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
52+
}
4953
} catch (error) {
50-
dispatch({ type: 'FETCH_FAILURE' });
54+
if (!didCancel) {
55+
dispatch({ type: 'FETCH_FAILURE' });
56+
}
5157
}
5258
};
5359

5460
fetchData();
61+
62+
return () => {
63+
didCancel = true;
64+
};
5565
}, [url]);
5666

5767
const doGet = (event, url) => {

0 commit comments

Comments
 (0)