I'm working on a navbar that changes whenever it detects there is a user in local storage using useState and useEffect. Here's my logic:
const [user, setUser] = useState("")
function fetchData(){
const item = JSON.parse(localStorage.getItem('name'))
if(item) {
setUser(item)
}
}
useEffect(() => {
fetchData()
});
return({user? (<LoggedIn />) : (<ClientBar />})
The code essentially begins with no user, and in the fetchData() function it checks whether a user exists in local storage and sets the user based on what's been found in local storage. I can tell the logic works because when I refresh it, it changes from <ClientBar> to <LoggedIn>. However, the problem is it doesn't work upon login - rather, it requires a refresh to update. Is there a way to make it update immediately upon login?
As Abhi Patil stated, you need to check localStorage changes. It has nothing to do with useEffect as it is only triggered when the component is mounted.
You need to wrap fetchData() inside storage event listener like so:
useEffect(() => {
window.addEventListener('storage', () => {
const item = JSON.parse(localStorage.getItem('name'))
if(item) {
setUser(item)
}
})
})
Your useEffect should be:
useEffect(() => {
fetchData()
}, [user])
So when user changes it will check each time. Because you're fetching localstorage I'd also encourage you to add a loading component while that's being done.
Checking localstorage Should also be using async/await:
const fetchData = async () => {
const item = await JSON.parse(localStorage.getItem('name'))
if(item) setUser(item)
}
While this it's waiting for the check you should render a loading with another useState.