Problem
This is my first time trying to add clean error handling and loading notification for async requests in my project. It looks kind of bulky to me, but maybe that’s because I’m inexperienced? This is what I have at the top of all my index-like components. I also thought maybe it was a good target for a custom hook, but I haven’t made any before.
getClasses
is a Redux thunk action, and classes
also comes from a Redux slice of state.
const ClassIndex = ({ classes, getClasses }) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
const fetchClasses = async () => {
try {
setIsLoading(true);
setError("");
await getClasses();
setIsLoading(false);
} catch (error) {
setIsLoading(false);
setError("There was an error finding your classes.");
}
};
fetchClasses();
return () => {
setError("");
setIsLoading(false);
};
}, [getClasses]);
Solution
For async requests I suggest you to use react-query package. Which return you isLoading
and isError
for per request. And you don’t need to create additional local state.
With react-query I can reduce all of your code just to 4 lines.
const { isLoading, data, error } = useQuery('key', async () => {
const res = await axios.get('link')
return res.data
})
isLoading
flag need to be converted to true in finally
case. Then we just remove unnecessary setIsLoading(false);
in catch
and after getClasses
request
const fetchClasses = async () => {
try {
setIsLoading(true);
setError("");
await getClasses();
} catch (error) {
setError("There was an error finding your classes.");
} finally {
setIsLoading(false);
}
};
fetchClasses();