Home > Software engineering >  React only saves state to localstorage when I double execute the function why?
React only saves state to localstorage when I double execute the function why?

Time:10-25

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

CodePudding user response:

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;
  });
}
  • Related