Home > OS >  Variable storage update across react component
Variable storage update across react component

Time:04-18

This is a next/react project. folder structure:

components > Navbar.js

pages > index.js (/ route)(includes Navbar)
      > submitCollection.js (/submitCollection)(includes Navbar)

I am trying to have the user submit a specific string as an input and i store it inside the account variable. Navbar.js

const Navbar = ({}) => {
    
    const [account,setAccount] = useState()
    
    const handleClick = () => {
        setAccount(randomNumberThatIHaveGenerated)
    }
    ...
    return (
        <Link href="/">home</Link>
        <Link href="/submitCollection">submit collection</Link>
        ...
        <button onClick={handleClick} >press to set account</button>
        ...
        {account?(<p>{account}</p>):(<p>u need to set an accout</p>)}
    )
}

when i visit home using the navbar link, the account is again set to undefineed and i need to press the button again in order to set it. How can i make the string remain set. like persist on the navbar

CodePudding user response:

You can solve this problem using localstorage and useEffect

Adding this piece of code to your work will do the trick

const [account,setAccount] = useState(localStorage.getItem('account') ?localStorage.getItem('account') : null)


useEffect(()=>{
localstorage.setItem(account)
},[account])

For example

const [account,setAccount] = useState(localStorage.getItem('account') ?localStorage.getItem('account') : null)
    useEffect(()=>{
localStorage.setItem('account',account)
},[account])
    const handleClick = () => {
        setAccount(randomNumberThatIHaveGenerated)
    }

Hope it helped

CodePudding user response:

useState is not persistent, it is bound to its component, in order to make it persist, you have to use localStorage

const [account,_setAccount] = useState();
const setAccount = (val) => {
  _setAccount(val);
  localStorage.setItem('account', val);
}

useEffect(() => {
  const storedAccount = localStorage.getItem('account');
  if (storedAccount) _setAccount(storedAccount);
}, [])
    
const handleClick = () => {
  setAccount(randomNumberThatIHaveGenerated)
}

useEffect is called when the component renders, check for stored account and displays it.

And notice how we reimplement setAccount, so that everytime it is called, we update the localStorage.

You can also create a custom hook with this logic, so the component would look cleaner. Or even better, use something like use-state-persist

  • Related