Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an async function inside the if condition of useEffect hook

How can I call a redux action inside the if block of useEffect hook:

useEffect(async () => {
    if (nameId && selectedGroup === 'AGM') {
        const subPeople = await getSubPeople(nameId);
    }
}, [nameId, selectedGroup]);

I have two select boxes. If the person types in the name select box, I store the selected id of name in the nameId state. If user selects a group, I store it in selectedGroup, so only if both conditions match I need to call an API endpoint to get the subPeople.

If I comment this code there is no error. How can I make the snippet work?

like image 325
Learner Avatar asked Sep 05 '25 03:09

Learner


1 Answers

You can move the async logic into a separate function and call it inside useEffect, since useEffect's callback can't be async itself:

useEffect(() => {
  const getPeople = async () => {
    if (nameId && selectedGroup === 'AGM') {
      const subPeople = await getSubPeople(nameId);
      return subPeople; // Or set the state, etc.
    }
  }
  getPeople(); 
}, [nameId, selectedGroup]);

like image 193
Clarity Avatar answered Sep 07 '25 21:09

Clarity