redux-thunk fetch parse response - javascript

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.

Related

what does <promiseResponse>.json() do?

in the following code
useEffect(() => {
fetch(options.url)
.then((response) => response.json()
.then((r) => setData(r)));
}, [options.url]);
what does response.json() do ? why do we need to do a .json(), would it be fine if one did not invoke that function?
response.json() reads the Response's body as a ReadableStream, parses it as JSON, and returns the parsed data in an asynchronous Promise.
Without doing this, you'd have the Response object, but you wouldn't be able to access the data inside it right away.

Why I am getting undefined while fetching data form API

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

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

Fetch YAML or MsgPack in Javascript (Browser)

I know how to fetch JSON with the Fetch API like this:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
I tried to replicate the same thing to get MsgPack or YAML data, but all my attempts have failed. I obviously know how to deserialize data, but I suspect I feel a bit lost with chained promises which I don't fully grasp. Since there is no response.yaml(), I need to us an extra step but I can't make it work. I tried with response.body() and response.blob(). Each time I do it, no data is available at the time of the console log. Which I assume means that my data is still a promise instead of being processed and called with the callback.
I have tried things like:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(data => console.log(deserialize(data)));
or:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(raw => deserialize(raw))
.then(data => console.log(data));
Here deserialize is a placeholder for the deserialize/decode function for either format.
Anybody has an example using YAML (I suspect more popular than MsgPack).
Maybe this npm package can help you with parsing yaml data: https://www.npmjs.com/package/js-yaml, https://github.com/nodeca/js-yaml.
example.yaml:
docker:
- image: ubuntu:14.04
- image: mongo:2.6.8
command: [mongod, --smallfiles]
- image: postgres:9.4.1
This works for me:
fetch('/example.yaml')
.then(res => res.blob())
.then(blob => blob.text())
.then(yamlAsString => {
console.log('yaml res:', yamlAsString)
})
.catch(err => console.log('yaml err:', err))
First we convert the result to a Blob. After that we call the text() method on it which converts the blob to a string.
https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

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...

Categories