Why I am getting undefined while fetching data form API - javascript

I am a beginner and I am learning JavaScript. I am trying to make some projects with API. I am using Unsplash API to fetch some data. But I am getting typeerror. In my JavaScript code, lines 4 to 7, I am trying to console.log the likes, views, and downloads but they are showing undefined.
fetch(`https://api.unsplash.com/photos/random/?client_id=YILDy9SO8bXBp_dwX7aFO3R_UAs1-8v0gTrK2o2wllE&count=1`)
.then(response => response.json())
.then(data => {
console.log(data);
console.log("Likes:", data.likes);
console.log("Views:", data.views);
console.log("Downloads:", data.downloads);
});
What is the problem? How can I get those values?

The data object returns in an array, so you have to get the 0th element to then access the object and its data. Like this:
fetch(`https://api.unsplash.com/photos/random/?client_id=YILDy9SO8bXBp_dwX7aFO3R_UAs1-8v0gTrK2o2wllE&count=1`)
.then(response => response.json())
.then(data => {
console.log(data);
console.log("Likes:", data[0].likes);
console.log("Views:", data[0].views);
console.log("Downloads:", data[0].downloads);
});

Related

Save JSON in Local Storage after the fetch

Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows PromiseĀ {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!
response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.
fetch(url + id)
.then( response => response.json() )
.then( json => {
localStorage.setItem('myResponse', JSON.stringify(json));
})
Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));

how to fetch data from promise object which is in json format

I'm trying to calculate distance from google api using fetch now i convert data into json which is in promise object and json fromat here is my code and also the screenshot of what I'm getting now
i try so far but getting undefined error every time.
fetch(proxyurl + re)
.then(function(response) {
console.log (response.json());
});
i want to get data of source and destination time and distance
here is the screenshot https://i.stack.imgur.com/Dz51R.png
Try to update your fetch method like this:
fetch('https://api-endpoint.com')
.then(response => response.json())
.then(data => {
console.log(data);
});
Demo with github users endpoint: https://codesandbox.io/s/prod-bush-wqn70

Fetch API call in Codepen vs. Postman

I'm attempting to collect some data from the Last.fm API. Using Postman, and with the call below, I am getting a response.
http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&api_key=4a9f5581a9cdf20a699f540ac52a95c9
When I try to achieve the same result on Codepen, I don't get a response. This is the code I'm using:
fetch("http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&api_key=4a9f5581a9cdf20a699f540ac52a95c9")
.then(response => response.json())
.then(data => console.log(data))
What am I missing here?
As both of the commenters mentioned
CORS issue: you can append https://cors-anywhere.herokuapp.com/(hacky work around)
specify the data type to be json...
Try this it should work:
fetch('https://cors-anywhere.herokuapp.com/http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=spain&format=json&api_key=4a9f5581a9cdf20a699f540ac52a95c9')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
Note: You should not share that API key...

Using fetch to get data from an API, how to access data after promise has resolved?

Running the below code on the console, I get an array of objects.
fetch('https://api.github.com/users/chriscoyier/repos')
.then(response => response.json())
.then(data => {
// Here's a list of repos!
console.log(data)
});
How can I access the data later? For example if I wanted to console.log the data[0].archive_url, after the promise has resolved? But that gives an error "Uncaught ReferenceError: data is not defined". How do I access that array of objects?
var myGlobalVar;
fetch('https://api.github.com/users/chriscoyier/repos')
.then(response => response.json())
.then(data => {
console.log(data);
myGlobalVar = data;
});
Once this request has finished (once you see the console output), the data is now available in the variable myGlobalVar for you to play around with on the console. You could also use your browser's debugger to set a breakpoint in the callback function and have direct access to data from there.
Note that this won't work in actual code, this is only useful for the interactive console: How do I return the response from an asynchronous call?

redux-thunk fetch parse response

I am new to redux and reactjs and I am trying to fetch some server side data to my code.
This is my thunk fetch:
fetch(`/WebApp/Dashboard/CreateAlert`).then(response => {
console.log(response);
});
This is what I see in the console:
In fiddler I see the response is "Success" as expected.
Is this response valid and how do I parse it, I am a bit confused and there is very little info online.
EDIT:
I changed to:
fetch(url).
then(response => response.json())
.then(json => {
console.log(json);
});
And I received the object. Now when I send a complex type(List), I see the bellow:
If you want to parse a json response:
fetch(`/WebApp/Dashboard/CreateAlert`)
.then(response => response.json())
.then(json => {
console.log(json);
});
See https://developer.mozilla.org/en-US/docs/Web/API/Body for all of the methods you can use to parse the response body.

Categories