Aexomir
Aexomir

Reputation: 176

Getting JSON info from API

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

Upvotes: 0

Views: 277

Answers (2)

Shing Ho Tan
Shing Ho Tan

Reputation: 951

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

Try this

Upvotes: 1

Zahra Mirali
Zahra Mirali

Reputation: 545

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

Upvotes: 1

Related Questions