I want to save colors arrays in localstorage but when execute the saveColors
function it just saves the former state, then I execute the saveColors
again and it works. Why is this behaviour occuring and how to solve it?
Here's the example above 2nd save must have included the 5 objects inside the array. But instead when I click save again it saves it with 5 objects.
const [savedColors, setSavedColors] = React.useState(JSON.parse(localStorage.getItem('colors')) || [] );
function saveColors(){
setSavedColors(prevSavedColors => (
[
...prevSavedColors,
data.colors
]
))
localStorage.setItem("colors", JSON.stringify(savedColors));
}
For full code: http://pastie.org/p/2xYK30wTkqsb94ZU0Wk2C5