-1

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

EQ92
  • 1
  • 1
    Add `useEffect(() => { console.log('data', data); }, [data]);` – Patrick Roberts Aug 03 '22 at 23:10
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Phil Aug 03 '22 at 23:32
  • There's really two problems here... 1) `getWeatherData` is async. You would need to wait for it to resolve before anything happens. 2) `data` will not be updated by a call to `setData()` until your component re-renders. This is explained in the duplicate link – Phil Aug 03 '22 at 23:35

1 Answers1

-1

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}>({});
David G.
  • 1,255
  • 9
  • 16
  • Not sure why I got downvoted here, while the `console.log` in the code won't show anything because of the async function, the OP mentions the data is there when they console.log it, they even added a screenshot. They mention Intellisense, so it would make sense for this to be a typescript error like I mentioned in my answer, maybe it is clearer in this example: https://stackblitz.com/edit/react-ts-tdhmjq?file=App.tsx – David G. Aug 04 '22 at 09:12