How to store data in localStorage in reactjs

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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])

Solution 2

Your code always set initial value for defaultAccount is null

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply