0

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?

enter image description here

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

Shifty
  • 47
  • 8
  • 2
    Does this answer your question? [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) – JBallin Oct 24 '22 at 16:35
  • 2
    setState is async. State hasn't updated yet on the first call, but it is updated by the time you make the second call. – JBallin Oct 24 '22 at 16:36
  • @JBallin What should I use instead of state hook? I didn't get how to fix it :/ – Shifty Oct 24 '22 at 16:43

1 Answers1

1

setState in react is async action therefore you didn't get what you wanted You can read this answer JBallin recommended to get reason for why it didn't immediately took effect

Here's how you can solve it

const [savedColors, setSavedColors] = React.useState(JSON.parse(localStorage.getItem('colors')) || []);

function saveColors() {
  setSavedColors(prevSavedColors => {
    // instead of returning right away create a new array and save it in local storage
    const updatedColors = [...prevSavedColors, data.colors];

    localStorage.setItem('colors', JSON.stringify(savedColors));

    return updatedColors;
  });
}
Arun Bohra
  • 104
  • 1
  • 10