score:0

Accepted answer

issue

the img tag loads all the images fine for the first call however, the problem is that when i do another zipcode and clicked search, the texts updated, but the img tag (the weather images) did not update ( i.e. first search 91001 everything looks great, searched again for 95133, name changed to san jose but the weather forecast images did not update from 91001's to 95133's)

you always append forecast data to the forecast state but only reference the first 8 elements.

response["daily"].foreach((day) => {
  setforcast((forecast) => [
    ...forecast, // <-- shallow copy persists old forecast data
    day["weather"][0]["icon"]
  ]);
});

...

<img
  src={`http://openweathermap.org/img/wn/${props.forecast[0]}@2x.png`}
  alt="forecast image"
/>

...

<img
  src={`http://openweathermap.org/img/wn/${props.forecast[1]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[2]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[3]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[4]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[5]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[6]}@2x.png`}
  alt="forecast image"
/>
<img
  src={`http://openweathermap.org/img/wn/${props.forecast[7]}@2x.png`}
  alt="forecast image"
/>

solution

to resolve, you should overwrite the forecast state when updating.

setforcast(response.daily.map((day) => day.weather[0].icon));

here's a "optimized" button click handler.

<button
  onclick={async () => {
    setloading(false);

    const weather = await currentweather(zipcode, apikey);
    setweatherdata(weather);
    console.log(weather);

    const forecast = await sevendayweather(
      weather.coord.lon,
      weather.coord.lat,
      apikey
    );
    setforcast(forecast.daily.map((day) => day.weather[0].icon));

    setloading(true);
  }}
>
  search
</button>

and for the sake of dry-ness, mapped forecast images.

{props.forecast.map((id, index) => (
  <img
    key={index}
    src={`http://openweathermap.org/img/wn/${id}@2x.png`}
    alt="forecast image"
  />
))}

Related Query

More Query from same tag