0
\$\begingroup\$

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]);
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Dec 8, 2021 at 15:33
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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();
answered Dec 9, 2021 at 10:41
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.