Weather hourly forecast with React and TypeScript

Weather hourly forecast with React and TypeScript

I try to only display the next 5 hours based on the current time in my weather app, but I don't know how do this.

This is my code:

   <div className="hour_forecast_container">
        {weatherData.forecast.forecastday[0].hour.map((i) => (
              <div>
              <div className="hour_container">
                <div>
                <p key={i.temp_c}>{i.temp_c}°C</p>
                <img src={i.condition.icon} height={"28px"} width={"28px"}/>
                <p key={i.time}>{convertDate(i.time)}</p>
                </div>
           </div>
           </div>
        ))}
        </div>

(the time is a type string).

Answer

You're on the right track! If you want to only show the next 5 hours from the current time, you need to filter your forecast data based on the current hour.

Here's how you can do it step-by-step:

Add this logic before the return statement in your React component:

const currentHour = new Date().getHours();

const nextFiveHours = weatherData.forecast.forecastday[0].hour.filter((hourData) => {
  const forecastHour = new Date(hourData.time).getHours();
  return forecastHour >= currentHour && forecastHour <= currentHour + 5;
});

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions