简体   繁体   中英

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

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

这是我的代码示例图片,带有一个伪造的 getService 函数,您可以在图片底部看到正确的日志

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

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM