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.
>Solution :
You need to decide what userType will hold. There’s a few issues:
useStateeither takes in an initial value, or a function that will evaluate the initial value. You are passing them both.- On the initial value function,
localStorage.getItem('userType')seems like it returns a JSON object (you do JSON.parse), whereas you aresetItem('userType', 'some string') useEffecttakes in an array of dependencies, you are passing in just the stringdefaultAccount- I don’t fully understand what that
useEffectdoes:defaultAccountcomes fromuserType, but then it setsuserTypein 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])