Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use fetch via js. It's returning as if its not actually calling any data. Where am I going wrong?

I’m having trouble finding any resources for this. All I need is help in the right direction to get something tangible to use in some HTML. So basically when I call console.log(keys) I don’t get the json objects in my console like I’m used to. Project specifically requests it be done this way via fetch.

function getFromSWAPI() {

    fetch("https://swapi.dev/api/people/1")
    .then(function (response) {
        return response.json()
    })
    .then(function(data){
        updateInfo(data)
    })
    .catch(function(err) {
        console.warn(err)
    })
}

const updateInfo = responseJSON => {
    console.log(responseJSON.data)
    let keys = Object.keys(responseJSON.data)
    console.log(keys)
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So basically there is a minor bug in your code,

In this line

{...}
.then(function (response) {
        return response.json()
    })
{...}

you have already returned the json and thus you are accessing it in the next line

{...}
.then(function (data) {
        updateInfo(data)
    })
{...}

As the returned data is itself the real data, you don’t have to reaccess it with the data property here

{...}
const updateInfo = responseJSON => {
    console.log(responseJSON.data)
    let keys = Object.keys(responseJSON.data)
    console.log(keys)
}

The finished code will look like this –

 function getFromSWAPI() {

    fetch("https://swapi.dev/api/people/1")
    .then(function (response) {
        return response.json()
    })
    .then(function(data){
        updateInfo(data)
    })
    .catch(function(err) {
        console.warn(err)
    })
}

const updateInfo = responseJSON => {
    console.log(responseJSON)
    let keys = Object.keys(responseJSON)
    console.log(keys)
}

Alternatively, I would suggest you use async/await if you are using fetch inside a function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading