Home > Net >  fetch data is updated but array and state is not updated
fetch data is updated but array and state is not updated

Time:12-22

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} />
    </>
  );
}

CodePudding user response:

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>
    </>
  );
}

  • Related