DEV Community

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

Posted on • Originally published at jetrockets.pro

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

Top comments (0)