Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the response data from promise in React?

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:

enter image description here

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!

like image 523
jjjjjjjj Avatar asked Dec 24 '22 15:12

jjjjjjjj


1 Answers

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)
})
like image 68
dama Avatar answered Dec 28 '22 09:12

dama