Home > Enterprise >  How to store data in localStorage in reactjs
How to store data in localStorage in reactjs

Time:06-01

I am trying to set up 2 types of users which are admin and anonymous and I am trying to store them in localStorage. So here, how I defined the account:

const [defaultAccount, setDefaultAccount] = useState(null, () => {
        const localData = localStorage.getItem('userType');
        return localData ? JSON.parse(localData) : [];
    });

And here is how I differentiate between admin and anonymous:

useEffect(() => {
    if (defaultAccount === '') {
        localStorage.setItem('userType', 'admin')
        setConnButtonText('Wallet Connected');
    } else if (defaultAccount === '') {
        localStorage.setItem('userType', 'nonexist')
    } else {
        localStorage.setItem('userType', 'anonymous')
        setConnButtonText('Wallet Connected');
    }
}, [defaultAccount])

But after I refreshed the page, even though I am an admin, it comes anonymous again. How can I fix this? So, to sum up, I click the button and get defaultAccount and I store userType as an admin. But then I refresh the page and it comes anonymous again. What I am trying to achieve, before the button is clicked, userType should be empty and after, it should be admin or anonymous. After refreshing the page, since it is stored in localStorage, it userType shouldnt be changed.

CodePudding user response:

You need to decide what userType will hold. There's a few issues:

  1. useState either takes in an initial value, or a function that will evaluate the initial value. You are passing them both.
  2. On the initial value function, localStorage.getItem('userType') seems like it returns a JSON object (you do JSON.parse), whereas you are setItem('userType', 'some string')
  3. useEffect takes in an array of dependencies, you are passing in just the string defaultAccount
  4. I don't fully understand what that useEffect does: defaultAccount comes from userType, but then it sets userType in the local storage only to "admin" or "anonymous"

Maybe something you're looking to do is something like:

const [defaultAccount, setDefaultAccount] = useState(() =>
  localStorage.getItem('userType') === 'admin' ? 'dgdsgd' : ''
)

useEffect(() => {
  if (defaultAccount === 'dgdsgd') {
    localStorage.setItem('userType', 'admin')
  } else {
    localStorage.setItem('userType', 'anonymous')
  }
}, [defaultAccount])

CodePudding user response:

Your code always set initial value for defaultAccount is null

  • Related