Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda