-3

I came from here so please don't mark it as a duplicate.

I'm trying to get every value of mainState to be placed in anotherState so at the end I have an array of arrays. mainState is an changes on hover and it changes a lot so I can't assign every value I have in it to anotherState, I only need the value when clicked.

const [mainState, setMainState] = useState([])
const [anotherState, setAnotherState] = useState([])
const [currentItem, setCurrentItem] = useState(0)

//mainState changes on hover and it can change a lot

const onClickHandler = () => {
  setAnotherState([...anotherState, mainState])
  if (currentItem >= 4) {
    // done with this component move to the next component
    } else {
      setCurrentItem(currentItem + 1)
      setMainState([])
    }
}

return (
<div onClick={onClickHandler}></div>

However, this doesn't work and even though mainState updates perfectly everytime, anotherState is always one step behind. currentItem represents an array index so I can't click one more time to get the last value of mainState in anotherState. I , using useEffect() which broke React because hover changes a lot and I ended up with an array of hundreds of values.

// tried useEffect() like in the question above, ended up with an array of hundreds of values

useEffect(() => setAnotherState([...anotherState, mainState]))

// tried using callback function like in one of the comments which didn't work and remained the same

setAnotherState(() => [...anotherState, mainState])

// another different way not using hooks is I created an empty array constant in the component 
// and on click I tried pushing the value of mainState to that array using deep copy
// I keep ending up with the last array pushed only

const arrays = []
const onClickHandler = () => {
  arrays.push(JSON.parse(JSON.stringify(mainState)))
}

How can I work around this?

G-8
  • 107
  • 1
  • 7
  • You already pointed out that you come from other question, as the answer states there, use functional update `setAnotherState(prev => ...)` – Dennis Vash Mar 13 '21 at 15:07
  • @DennisVash I tried that but the state still doesn't update immediately – G-8 Mar 13 '21 at 15:27

1 Answers1

0

setAnotherState is asynchronous. So if you want to get latest update value of anotherState.

You should use useEffect like

useEffect(() => 
Console.log("anotherState",anotherState)
// Do your stuff 
,[anotherState])

This hook will called whenever another state gets updated using setAnotherState.

ajay 24
  • 304
  • 3
  • 13