Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fetch data is updated but array and state is not updated

i am woking on weather api and storing perticular data in an array arr but value is not available in arr. also state arrdata is null too.
i tried to not use state but still not getting data in arr . it show reading undefined value.

export default function App() {
  const [cityName, setCityName] = useState("delhi");
  const [arrData, setArrData] = useState(null);
  const getWeatherInfo = async () => {
    const url = "https://api.openweathermap.org/data/2.5/forecast";
    const api = "4beffc863037e89f0f181d893d1cf79b";
     fetch(`${url}?q=${cityName}&units=metric&appid=${api}`)
      .then((res) => res.json())
      .then((getData) => {     
      if(getData.list[4].main !== null){
        const arr = [];
        for (let i = 0; i <= 40; i++) {
          if (i % 8 === 0) {
            arr.push({
              temprature: getData.list[i].main.temp,
              Min_temp: getData.list[i].main.temp_min,
              Max_temp: getData.list[i].main.temp_max,
              date: getData.list[i].dt_txt,
              mood: getData.list[i].weather[0].main,
              weathermoodIcon: getData.list[i].weather[0].icon,
              Humidity: getData.list[i].main.humidity,
            });
          }}
        setArrData(arr);
      }});
  };
  useEffect(() => {
    getWeatherInfo()
  }, []);
 console.log(arrData)
  const onInputChange = (e) => {
    setCityName(e.target.value);
  };

  const onSubmitCity = () => {
    getWeatherInfo();
  };

  return (
    <>
      <Input onChangeValue={onInputChange} onSubmit={onSubmitCity} />
    </>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This seems to be working. Please do not forget to use optional chaining

import {useState, useEffect } from 'react';
export default function App() {
  const [cityName, setCityName] = useState("delhi");
  const [arrData, setArrData] = useState(null);
  const getWeatherInfo = async () => {
    const url = "https://api.openweathermap.org/data/2.5/forecast";
    const api = "4beffc863037e89f0f181d893d1cf79b";
     fetch(`${url}?q=${cityName}&units=metric&appid=${api}`)
      .then((res) => res.json())
      .then((getData) => {     
      if(getData.list[40]?.main !== null){
        const arr = [];
        console.log(getData.list)
        for (let i = 0; i <= 4; i++) {
          if (i % 8 === 0) {
            arr.push({
              temprature: getData.list[i]?.main.temp,
              Min_temp: getData.list[i]?.main.temp_min,
              Max_temp: getData.list[i]?.main.temp_max,
              date: getData.list[i]?.dt_txt,
              mood: getData.list[i]?.weather[0].main,
              weathermoodIcon: getData.list[i]?.weather[0].icon,
              Humidity: getData.list[i]?.main.humidity,
            });
          }}
        setArrData(arr);
      }});
  };
  useEffect(() => {
    getWeatherInfo();
  
  }, []);

 console.log(arrData)
  const onInputChange = (e) => {
    setCityName(e.target.value);
  };

  const onSubmitCity = () => {
    getWeatherInfo();
  };

  return (
    <>
      <input  onChange={onInputChange} onSubmit={onSubmitCity} />
      <h1> {JSON.stringify(arrData)} </h1>
      <button onClick = {onSubmitCity}> Submit </button>
    </>
  );
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading