Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React state setter function not changing the state

I am working on a history component in my React project. I have the history state and a setter function setHistory() . I have two functions for handling clicks: handleClick() and removeHistoryItem(), which are called with different buttons. In both of them, I am changing the state with the setHistory() function, but it doesn’t work in the handleClick() one.

const removeHistoryItem = () => {
    const newHistory = history.filter(item => item.id != id)
    setHistory(newHistory)
}
    
 const handleClick = () => {
    let newHistory = history
    let [selectedGame] = history.filter(item => item.id == id)
    const index = history.indexOf(selectedGame)
    
    selectedGame.isFavorite = !selectedGame.isFavorite
    newHistory.splice(index, 1, selectedGame)
    localStorage.setItem('history', JSON.stringify(newHistory))
    setHistory(newHistory)
}

The functions are next to each other so there shouldn’t be a problem with the scope. Both functions are executing the other operations well (tested with console.log(), the localStorage is changed just fine, the splice and filter functions are working also). Even the value I am passing to the setHistory() function is correct, just the state is not changed. It’s like the setHistory() function is not even called. I am not getting any errors, what could the problem be?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Error is due to Reference equality, both newHistory and history in your handleClick function are referencing same array in "memory", which you mutate with splice, but it is still the same object, react will not detect the change and will not fire the rerender, just because oldValue (history) === newValue (newHistory).

So you need to "recreate" the array in this case. For removeHistoryItem all is ok due to .filter returns the new array already, so new reference, new object.

setHistory([...newHistory]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading