Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda