0

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

1 Answer 1

3

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

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.