Home > Net >  how can i solve undefined in my code while pulling data from a REST API
how can i solve undefined in my code while pulling data from a REST API

Time:09-07

i'm pulling data from a json file

[
    {
        "name": "Charlie S. Gerardi",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/brad_frost/128.jpg",
        "id": 75,
        "occupation": "Residential electrician"
    },
    {
        "name": "Riley D. Norris",
        "avatar": "",
        "id": 23,
        "occupation": "Transmission engineer"
    }
]

when I console.log(data) am capable to see the json file

<script>
    const api_url='https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=key4v56MUqVr9sNJv'
    async function getAirtable() {
        const response = await fetch(api_url);
        const data = await response.json();
        console.log(data.name)
        console.log(data.id)           //am not able to see the values in my consol//
        console.log(data.avatar)
        console.log(data.occupation)
    }
    getAirtable()
</script>

CodePudding user response:

Based on your JSON, data is an array, so if you want to see everything, you need to iterate through the array such as

data.forEach(item => console.log(item.id))

CodePudding user response:

To access your data try this logic by looping through the items

const api_url = "https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=key4v56MUqVr9sNJv";

async function getAirtable() {
  const response = await fetch(api_url);
  const data = await response.json();
  const allData = data.records.map((rec) => rec.fields);
  //   allData = [
  //     {
  //       Id: 79,
  //       Name: "Julia A. Robles",
  //       avatar:
  //         "https://s3.amazonaws.com/uifaces/faces/twitter/pixeliris/128.jpg",
  //       occupation: "Prosthodontist",
  //     },
  //     {
  //       Id: 29,
  //       Name: "Matthew H. Glover",
  //       avatar:
  //         "https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg",
  //       occupation: "Transportation attendant",
  //     },
  //   ];
  console.log(allData);
}
  • Related