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

126
Vistas
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);
      }
    };

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It looks like you want to transform each element in res2.data.list into a new object, then set that new list on React state.

.map is used for 1-to-1 list transformations.

So setForecast(res2.data.list.map(e => ({dt_txt: e.dt_txt, etc}))

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar
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