Getting JSON info from API

258 Views Asked by At

I'm using Axios(Apisauce) to connect API to React Native App; this is the JSON file I'm trying to show in-app using FlatList :

{
  "data": {
    "sideMenu": {
      "url": "https://google.com",
      "icons": [
        {
          "id": 1,
          "url": "https://google.com",
          "status": 1
        },
      ]
    },
  }
}

when I try to log it into the console, using console.log(response.data) returns all API info, but using console.log(response.data.data) doesn't return the object I'm looking for!

I've tried JSON.stringify() or toString() but none of them seem to Work.

my Axios Code :

const getServices = () => {
  const service = "https://api.team-grp.ir/app/json/services2.json/";

  return client.get(service);
};

My Source Code:

  const ServiceInfo = async () => {
    await getServices()
      .then((response) => {
        if (response.ok) {
          setServicesData(response.data.data);
        }
      })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };


useEffect(() => {
ServiceInfo();
});
2

There are 2 best solutions below

1
On

you should not use async/await with .then/.cache ... this code is working for me: (you can also see my sample code image at the bottom of this answer with a fake getService function, and you will see that logged response is correct)

const ServiceInfo = () => {
    getServices().then((response) => {
        if (response.ok) {
          setServicesData(response.data.data);
        }
      })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };


useEffect(() => {
   ServiceInfo();
}, []);

here is my code sample image, with a fake getService function, you can see the correct log at the bottom of image

0
On
const ServiceInfo = async () => {
    await getServices()
      .then((response) => {
          return response.json();
      })
      .then((response) => {
         setServicesData(response.data);
       })
      .catch((error) => {
        console.warn(error);
        setServicesData([]);
      });
  };

Try this