Iterate through JSON array putting into new array

Having problems iterating through JSON array with for loop (res2.data.list), grabbing three data points, and putting them into a new array. Getting error “forecast is not a constructor in fetchWeather”. How would I do this in a functional component?

const fetchWeather = async () => {
        
      try {
        await window.navigator.geolocation.getCurrentPosition(
          savePositionToState
        );
        const res = await axios.get(
          `${process.env.REACT_APP_API_URL}/weather?lat=${latitude}&lon=${longitude}&appid=${process.env.REACT_APP_API_KEY}&units=imperial`
        );
        const res2 = await axios.get(
          `${process.env.REACT_APP_API_URL}/forecast?lat=${latitude}&lon=${longitude}&appid=${process.env.REACT_APP_API_KEY}&units=imperial`
        );
        setTemperature(Math.round(res.data.main.temp));
        setWeather(res.data.weather[0].main);
        console.log(res2.data.list)

        // console.log(res.data, res2.data);
            for (let i=0; i < res2.data.list.length; i+=1) {
                const temporary = new forecast(
                    res2.data.list[i].dt_txt,
                    res2.data.list[i].weather[0].icon,
                    res2.data.list[i].main.temp,
                    res2.data.list[i].dt_txt,
                    )
            }


    } catch (err) {
        console.error(err);
      }
    };

Answer

Given const [forecast, setForecast] = useState([]); I’ll assume you want forecast to be an array of objects with the specific properties from res2.data.list response array. forecast is the state object, it’s not a constructor, so trying to invoke a new forecast won’t work.

You can map the res2.data.list to a new array and update the forecast state.

const fetchWeather = async () => {
  try {
    await window.navigator.geolocation.getCurrentPosition(
      savePositionToState
    );
    const res = await axios.get(.....);
    const res2 = await axios.get(.....);

    setTemperature(Math.round(res.data.main.temp));
    setWeather(res.data.weather[0].main);

    setForecast(res2.data.list.map(item => ({
      text: item.dt_txt,
      icon: item.weather?.[0]?.icon,
      mainTemp: item.main?.temp,
    })));
  } catch (err) {
    console.error(err);
  }
};