I'm following the nice article "How to fetch data with React Hooks?", in particular the section "ERROR HANDLING WITH REACT HOOKS".
There we have a useEffect that depends on the url where we fetch data from.
fetchData();
}, [url]);
The url is set on a submit from an input, specifying the query string.
<form
onSubmit={() =>
setUrl(`http://hn.algolia.com/api/v1/search?query=${query}`)
}
>
My problem is that, even if the author defines
The error is just another state initialized with a state hook
and he implements the try/catch block for error handling and he finally concludes:
The error state is reset every time the hook runs again. That's useful because after a failed request the user may want to try it again which should reset the error.
actually I see that the useEffect to fetch data depends only on the url, that is the query string, hence, if the user doesn't change the query string, he can't try again. This can be useful especially to try after an error, but even more in general. How to achieve this goal?
I've tried
fetchData();
}, [url, isError]);
but it gets stuck in a loop of updates...
My solution for this problem was
to add another hook state (representing the need to repeat the data fetch):
to make the
useEffectdependent on it (also adding acleanup):and finally adding a check in the
submitto force the data fetch even if thequerystring wasn't changed: