4

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Learner
  • 8,379
  • 7
  • 44
  • 82
  • someone wrote a `useAsyncEffect` thing just for this ... also there's [this question on SO that may help](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – Bravo Nov 22 '19 at 08:42

1 Answers1

5

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

Clarity
  • 10,730
  • 2
  • 25
  • 35