Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
UseEffect to update navbar when user is logged in?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
    }
 })
})
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!