Home > Mobile >  UseEffect async actions
UseEffect async actions

Time:12-15

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);
}, []);

CodePudding user response:

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

CodePudding user response:

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);
}, []);
  • Related