user11130509
user11130509

Reputation:

saving state into localstorage in react

I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }

state info:

const[info,setInfo]=useState([])

Upvotes: 1

Views: 630

Answers (3)

hendrixchord
hendrixchord

Reputation: 5434

setInfo i.e. setState is async. You need to use useEffect for this.

    useEffect(() => {
        localStorage.setItem('state', JSON.stringify(info));
    }, [info]); // run whenever info is changed

Every time the state i.e. info is changed it will enter the useEffect block and update the local storage.

Upvotes: 0

Yousaf
Yousaf

Reputation: 29282

setInfo function will update the state asynchronously so when you call localStorage.setItem function and pass info in it, info array hasn't been updated yet.

You can create an array and pass it to setInfo and setItem function. This way, you don't have to depend on setInfo function to update the state before you save it in localStorage

const add = () => {
   if(website){
      const arr = [...info,{website:website,password:generate()}]
      setInfo(arr);
      localStorage.setItem("data",JSON.stringify(arr));
   }
}

Upvotes: 1

snaksa
snaksa

Reputation: 577

setInfo change will be available on the next render. You should calculate the value in a separate variable and then set it.

const add=()=>{
  if(website){
    let value = [...info,{website:website,password:generate()}];
    setInfo(value)
    localStorage.setItem("data",JSON.stringify(value));
  }
}

Upvotes: 0

Related Questions