DEV Community

Александр
Александр

Posted on • Originally published at jetrockets.pro

1 1

Redux async actions. Tracking loading and errors with React hooks.

If you use redux and async actions, then you probably had to deal with a situation where you need to monitor the loading and error status of this action. With the advent of hooks, it became possible to conveniently transfer this logic to one block and use it everywhere.

import { useState, useCallback } from 'react';
import { useDispatch } from 'react-redux';

function useAsyncAction(action, dependeces = []) {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const asyncAction = useCallback(
    (...args) => {
      async function callback() {
        setLoading(true);
        try {
          const res = await dispatch(action(...args));
          setIsError(false);
          setLoading(false);
          return res;
        } catch (e) {
          setLoading(false);
          setIsError(true);
          return e;
        }
      }
      callback();
    },
    [action, ...dependeces],
  );

  return [asyncAction, loading, isError];
}

Now you can use this hook in your functional component.

// …
  const [load, loading, isError] = useAsyncAction(() => loadActivityRequest(applicationId), [applicationId]);
// …
  load();

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →