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]);