I know this question has been asked a lot - but I need some help!
I would like getExistingCards()
to execute and setCards
before updateActivity()
.
getExistingCards()
should setCards
if 1) cards exist, and 2) cards
is an empty array (I don't want to setCards to existingCards
if cards
is already set to existingCards
!)
The below works perfectly, so this shouldn't have to change.
const [cards, setCards] = useState([]);
useEffect(() => {
updateActivity(path, cards);
}, [cards]);
Adding getExistingCards()
below causes an infinite loop (which makes sense because I know I'm setting state within the effect, and cards is also in the dependency array):
// useLayoutEffect executes before useEffect
useLayoutEffect(() => {
const getExistingCards = () => {
if (activity) {
if (path.field === "activity_milestones" || path.field === "activity_indicators") {
let existingItems = activity[path.field]
if (existingItems) {
setCards(existingItems);
}
}
}
};
getExistingCards();
}, []);
useEffect(() => {
updateActivity(path, cards);
}, [cards]);
I also tried to add both updateActivity()
and getExistingCards()
to the useEffect
implementing async/await, but realize getExistingCards()
is not actually a promise.
Any insight would be really appreciated - thank you
Just check the length of cards before your execute your embedded function
useEffect(() => {
if (cards.length === 0) updateActivity(path, cards);
}, [cards]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.