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:
useState
either 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')
useEffect
takes in an array of dependencies, you are passing in just the stringdefaultAccount
- I don't fully understand what that
useEffect
does:defaultAccount
comes fromuserType
, but then it setsuserType
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