简体   繁体   中英

(React.js) how to get the current value of localStorage?

I'm trying to sync the localstorage and the state with react hooks but I can't get the correct value even if I set a setTimeout() ,

for example, I'm trying to save a new key in the array, and if I print the state or the local Storage directly, I still get the previous state, but if print the state after the return of the component I get the correct value, how can I work this?

Like this I still get previous state,

const onSave = () => {
 setState(prevState => [...prevState, {...newState}])            
 localStorage.setItem('localState', JSON.stringify(state)) ;          
 console.log(JSON.parse(localStorage.getItem('localState')))   <--  //still getting the previous state :(
}

but if I do something like this, then I get the correct value, but I can't set the localstorage correctly or can I ?

const App = (props) =>{
 const onSave = () =>{
  setState(prevState => [...prevState, {...newState}])            
  localStorage.setItem('localState', JSON.stringify(state)) ; 
 }
 return(
 <div>
  { console.log(JSON.parse(localStorage.getItem('localState'))) }  <<-- correct state, wrong place
</div>
 )  
} 

thank you guys!

setState function is asynchronous, as you are immediately saving data to local storage it is saving the old state itslef

try changing your function to

const onSave = () =>{
  setState(prevState => [...prevState, {...newState}])            
}
useEffect(() => {
  localStorage.setItem('localState', JSON.stringify(state)) ;          
  console.log(JSON.parse(localStorage.getItem('localState'))) 
}, prevState)

Code :

var cookieValue = document.getElementById("demo");      
        var value = cookieValue.getAttribute('value');
        if(typeof(Storage)!=="undefined")
        {
            console.log(value);
            localStorage.setItem("GetData" , value);
            console.log(localStorage.getItem("GetData"));

        }

    function loading()
    {
            console.log("coming");
            var allcookies = localStorage.getItem('GetData');
            console.log(allcookies);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM