1

I want to fetch some data from a database, and depending on the user the returned data should differ. The way i tried it, was by passing the userid as a query. The id is stored as a redux state. The problem is, that it takes some time before the redux state is available. Ive tried fixing this with if statements, and rerunning the useEffect everytime the auth state is updated. This doesn't work.

I want to fetch, when the redux state auth.user.id is available. Which it is like .1 sec after the initial load.

Here is my code:

const auth = useSelector((state) => state.auth);
  useEffect(async () => {
    if (auth.token.length > 0) {
      const res = await getData(`calendar/?userId=${auth.user.id}`);
      setLessons(res.lessons);
      setEvents(res.events);
    }
  }, [auth, date]);
Jonas Hendel
  • 578
  • 4
  • 17

2 Answers2

1

I believe useEffect is already asynchronous, so you don't need to use the async keyword in the anonymous callback. You can create the async function for that logic elsewhere and call it within the useEffect.

Similarly, you could put in self calling async function within your useEffect as such:

useEffect(() => {
    (async () => {
      if (auth.token.length) {
        try {
          const res = await getData(`calendar/?userId=${auth.user.id}`);
          setLessons(res.lessons);
          setEvents(res.events);
        }catch (err) {console.log(err);}
      }
    })();
  }, [auth, date]);

I think this link may be helpful: React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Shah
  • 2,126
  • 1
  • 16
  • 21
-1

So with the basic understanding, I assume that you need to call the API whenever userId is available. try the below useEffect

  useEffect(async () => {
    // check user id is available here
    if (auth.user && auth.user.id) {
      const res = await getData(`calendar/?userId=${auth.user.id}`);
      setLessons(res.lessons);
      setEvents(res.events);
      // some other statements
    }
  }, [auth, date]);
Sarath
  • 2,318
  • 1
  • 12
  • 24