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));
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.
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.
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);
});
I've been looking for this over and over but cant find the proper answer
Using Fetch, in order to throw errors when getting status other than ok we must do it manually.
The back end is providing with an specific message about the error along the 401,404 etc, error code.
I want to access to it on my fetch but dont know how.
.then((response) => {
if (response.ok) {
return response.text();
}
else {
throw new Error(response.text()); ///THIS DOES NOT WORK.
}
})
.then(result => alert ("Added Successfully"))
.catch(error =>alert (error.message)); ///AND OF COURSE NEITHER DOES THIS.
You should console log your response and see what it contains. You also have to access the response object like this: response.text. You access it like its a function. You probably also have to parse the response before you access anything. Even though you didnt post the content of the response, the following snippet should point you into the right direction.
Check the snippet below which shows you a successfull error handling.
fetch("http://httpstat.us/404")
.then( response => {
if (!response.ok) {
throw new Error(response)
}
return response.json()
})
.catch( err => {
console.log(err.message);
})
I am setting up a very basic react app, and trying to call my local host server (separate backend server), which has JSON data on it. I want to extract the data returned from the promise, but nothing I do seems to work. Here is my code:
fetch('http://localhost:8080/posts')
.then(function(response) {
const items = response.json()
console.log(items)
})
I have tried response.json(), response.body, I tried logging the body with .then(functio(body) { console.log(body)}), response.data, response.body, but nothing works. Here is what the console prints out:
How can I take the output it is giving me, and get it in an array that I can iterate through? The "content" and "id" are what I need access to.
and FYI, the array, when i go to localhost:8080/posts in my browser is simple:
[{"id":1,"content":"hello, this is post 1"}]
any help is appreciated, thanks!
The call toresponse.json()will also return a promise so you need too handle that also. Try the code below.
fetch('http://localhost:8080/posts')
.then(function(response){ return response.json(); })
.then(function(data) {
const items = data;
console.log(items)
})