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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.