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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With