1

In my useEffect hook i have a few API requests, like:

useEffect(() => {
    dispatch(action1());
    dispatch(action2());
    dispatch(action3());
}, []);

How can i use 'loading' parameter inside hook using async/await function to have loading as true before dispatching first request, and as false after dispatching last request. Like:

const [loading, setLoading] = useState(false);

useEffect(() => {
    setLoading(true);
    dispatch(action1());
    dispatch(action2());
    dispatch(action3());
    setLoading(false);
}, []);

2 Answers2

1

You can do it like this:

const [loading, setLoading] = useState(false);

useEffect(() => {
  async function fetchData() {
    setLoading(true);
    await dispatch(action1());
    await dispatch(action2());
    await dispatch(action3());
    setLoading(false);
  }
  fetchData()
}, []);

Read more about useEffect and async: React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
  • `awiat dispatch` isn't actually waiting to action finish it process at the reducer – Hagai Harari Dec 14 '21 at 12:16
  • @HagaiHarari You have to configure your dispatcher to do so: You can just wrap everything into an promise. https://stackoverflow.com/questions/41930443/how-to-async-await-redux-thunk-actions – Lars Flieger Dec 14 '21 at 13:11
0

I always create a custom hook and use that for API call and redux dispatch. have a look this might help.

const useAction = () => {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);

  const fetchData = async (params) => {
    setLoading(true);
    try {
      // do something
      // await call api
      dispatch(action1());
      dispatch(action2());
      dispatch(action3());
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  return { fetchData, loading };
};

// Component
const { fetchData, loading } = useAction();
useEffect(() => {
  fetchData(params);
}, []);
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37