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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With