Home > Blockchain >  Axios returns object but useState hook wont set
Axios returns object but useState hook wont set

Time:08-04

Ive searched for problems like this but haven't found solution yet. When I console.log(data) I see the object with all the proper data. When i try to access it with data.name(or any other property on the object) nothing happens, even intellisense doesn't have anything for it.

const key = process.env.REACT_APP_WEATHER_API_KEY;
   const [data, setData] = React.useState<{}>({});

   const url = `https://api.openweathermap.org/data/2.5/weather?q=Lethbridge&units=imperial&appid=${key}`;

   const getWeatherData = async () => {
      if (longitude && latitude !== undefined) {
         axios
            .get(url)
            .then(response => {
               const returnedData = response.data;
               setData(returnedData);
            })
            .catch(err => console.log('Error:', err));
      }
   };

   React.useEffect(() => {
      getWeatherData();
      console.log('data', data);
   }, []);

When i console.log('data') though i see the object returned from api request proper like this.

Console logged return from api

CodePudding user response:

You are fetching some data that is not typed (or at least you are not using the type in your code. You are getting data from axios that is typed as any, because axios doesn't know anything about its type. Now when you use that data to set it to the state with setData, the data will take the type you have given to the state, in this case {}, an empty object, hence why you can't access any properties. You need to shape that object, declare a type for the data you are receiving and set it to the state. If you declare the state like this, you will be able to access the property name:

const [data, setData] = React.useState<{name: string}>({});

CodePudding user response:

I'm assuming you need to do JSON.parse(data) before you can access it.

Either that or you're attempting to access it before the value has been set in the in the .then.

  • Related