Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda