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.
Related
I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then(function(response) {
console.log(response)
response.forEach(i => console.log(i.name));
}).catch(function(err) {
console.log(`Error: ${err}` )
});
The error i get is
response.map is not a function
so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error
SyntaxError: Unexpected token o in JSON at position 1"
Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.
If anyone could point me in the right direction, I would be really grateful.
The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
// use the json
});
Understanding promises is key to using the fetch API.
At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.
fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
// response.json() returns a promise, use the same .then syntax to work with the results
response.json().then(function(users){
// users is now our actual variable parsed from the json, so we can use it
users.forEach(function(user){
console.log(user.name)
});
});
}).catch(err => console.error(err));
It appears that you might be accessing the json incorrectly. You could try calling response.json() instead.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then((response) => {
response.json().then((jsonResponse) => {
console.log(jsonResponse)
})
// assuming your json object is wrapped in an array
response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
console.log(`Error: ${err}` )
});
This example is structured to match your example, but ideally, you would return response.json() on that first .then block and proceed on the next block. Here is a similar example that proceeds on the next block.
In your particular case, you can view the Fetch API as a json aware wrapper for "XMLHttpRequest"s. Main differences being that the Fetch API is simpler, functional-like, and has convenience methods. David Walsh does a reasonable comparison in his blog post, which I recommend you take a look at. Plain "XMLHttpRequest"s just pass you whatever string was sent back from the server, it has no idea it could be JSON, and thus leaves it to the user to parse the response whatever way they see fit.
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));
Take a simple API fetch call, such as follows:
fetch('https://api.nasa.gov/planetary/apod?api_key=xxxxxxxxx')
.then(res => res.json())
.then(data =>setPic(data.hdurl))
I'm still a bit confused about how this works. My understanding is this - information is sent from the web server as JSON, but to displayed on a web page it has to be converted into a normal JS object. Is this correct?
And if so, how does the above method convert JSON to a JS object? Because as I understand it, res.json simply extracts the JSON, it doesn't convert it.
[...] how does the above method convert JSON to a JS Object? Because
as I understand it, res.json() simply extracts the JSON, it doesn't
convert it.
This is what .json() does - it resolves the JSON string and parses it into a JS Object:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as JSON and parse into a JS Object
.then(res => res.json())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
If you want the JSON String to remain a JSON String, you can use .text() instead:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as a string
.then(res => res.text())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
how to parse json from an url into html by using javascript (programmatically) and i facing an problem with this ?
api: https://corona.ps/API/summary
You need to use the built in JavaScript fetch() method which returns a promise. Use .then() to handle the response and .catch() to handle any errors relating to the fetch call.
Here's an example function using your api link:
function getData () {
fetch("https://corona.ps/API/summary")
.then(res => res.json())
.then(data => console.log(data)) // will log js object
.catch(err => console.log(err))
}
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.