Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 === "dgdsgd") {
            localStorage.setItem('userType', 'admin')
        } else {
            localStorage.setItem('userType', 'anonymous')
        }
    }, 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading