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

150
Views
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
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!