Sachu
Sachu

Reputation: 187

localStorage saving non updated state even though it comes after setState

I am using states to track various colors, and When the user switches to night mode it updates state and changes the colors of components. I am using localStorage to store these changes but it's storing the opposite of the correct color schemes. So it would correctly display a black background for night mode, but save a white background which should be for day mode. The code is below (third snippet of code which is the function is the most important).

Initial Colors

const [nightMode, setNightMode] = React.useState({
   background: "#FFFFFF",
   banner: "#55BAF1",
   bannerText: "#FFFFFF",
   listText: "#000000",
   inputBackground: "FFFFFF",
});

Updates night mode object

React.useEffect(() => {
  const sessionSettings = JSON.parse(localStorage.getItem("startupNightMode")) || [];
  setNightMode(sessionSettings);
}, []);

Function that switches color scheme

function switchNightMode(){
  if(isNightMode){ 
    setIsNightMode(false);  
  }
  else{
    setIsNightMode(true);
  }

  if(isNightMode){
    setNightMode(
      {
        background: "#413250", 
        bannerText: "#413250",
        listText: "#FFFFFF", 
        banner: "#FFFFFF",
        inputBackground: "#465C68"
      });   

      localStorage.setItem("startupNightMode", JSON.stringify(nightMode));   //SAVES OPPOSITE
  }
  else{
    setNightMode({
      background: "#FFFFFF" ,
      bannerText: "#FFFFFF" ,
      listText: "#000000",
      banner: "#55BAF1",
      inputBackground: "#465C68"
    });

    localStorage.setItem("startupNightMode", JSON.stringify(nightMode));   //SAVES OPPOSITE
  }
}

The state was updated and then it was saved in localStorage so I'm not sure why the non updated version is being saved.

Upvotes: 0

Views: 33

Answers (1)

Emre Koc
Emre Koc

Reputation: 1588

Setting state is asynchronous, so it might not be updated before you push it to localStorage. Use a variable instead:

const mode = isNightMode ? {
    background: "#413250", 
    bannerText: "#413250",
    listText: "#FFFFFF", 
    banner: "#FFFFFF",
    inputBackground: "#465C68"
} : {
    background: "#FFFFFF" ,
    bannerText: "#FFFFFF" ,
    listText: "#000000",
    banner: "#55BAF1",
    inputBackground: "#465C68"
};

setNightMode(mode);

localStorage.setItem("startupNightMode", JSON.stringify(mode));

Edit: updated to have the code simplified by replacing the if/else with a ternary operation

Upvotes: 1

Related Questions