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

155
Visualizações
Can't access variable defined in a react component

I am making a weather app, my code looks something like this:

const Home = () => {
  const [weather, setWeather] = useState(null);
  useEffect(() => {
    // ...
    setWeather(weatherIGotFromAPI)
  })
  
  if (weather.current.dt < weather.current.sunrise - 1800 || weather.current.dt > weather.current.sunset + 1800) {
        const timeOfDay = "night"
    } else if (weather.current.dt > weather.current.sunrise + 1800 || weather.current.dt < weather.current.sunset + 1800) {
        const timeOfDay = "day"
    } else {
        const timeOfDay = "dawnOrDusk"
    }

  
  return (
    <p>{timeOfDay}</p>
  )
}

When I start the code, it says 'timeOfDay is not declared'. I can fix the issue by creating the timeOfDay variable outside of the if statement and then modifying it. I also know I can create a separate state for timeOfDay. But my question is why I have to do this? Is there something fundamental here I don't understand?

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