Reputation: 1663
I'm trying to set state of array from grand child component which is located in parent component.
I tried to use setNumberOfVar([...varsLines]);
this method but it's not updating the state immediately.it updates but one step back.
My Code
const removeVar = (e, val) => {
e.preventDefault();
var varsLines = numberOfVar;
varsLines = numberOfVar.filter((item) => {
return item.postion != val;
});
varsLines = varsLines.map((item) => {
return {
...item,
postion: item.postion > val ? item.postion - 1 : item.postion,
};
});
console.log(varsLines);
setNumberOfVar([...varsLines]); // <== this line is not updating the state immediately;
console.log(numberOfVar);
};
Upvotes: 3
Views: 61
Reputation: 2806
setNumberOfVar() is an async operation and will not update state immediately.
If you want to get something like a callback when the state is updated, you can use the useEffect hook that runs on state update.
import {useEffect } from 'react';
useEffect(() => {
console.log(numberOfVar);
},[numberOfVar]);
Upvotes: 3
Reputation: 54
try to do something like this
setNumberOfVar(prevState=>prevState.filter().map())
use your own conditions in filter and map and see if it's working or not.
Upvotes: 1