Reputation: 324
I tried to calling a function more then 2 times using useEffect hook but the result it only calling that function with last call.
here is my code and try :
const [ selectValues, setSelectValues ] = useState([]);
const selectHandler = (e) => {
const filteredValues = selectValues.filter((i) => i.id !== e.id);
setSelectValues([ ...filteredValues, e ]);
};
useEffect(() => {
const obj1 = {...}
const obj2 = {...}
selectHandler(obj1)
selectHandler(obj2) // this is the only object will be saved to the state
},[])
I hope that issue explained properly
Upvotes: 0
Views: 83
Reputation: 3337
To be able to save any intermediate values from the state, you should update it in a callback manner, because selectValues
contains the value which was there when component was rendered (initial value in our case).
const selectHandler = (e) => {
setSelectValues((prevValues) => [...prevValues.filter((i) => i.id !== e.id), e]);
};
Upvotes: 3