Gil Gil - 2 months ago 6
JSON Question

Get data from fetch React

I'm trying to get data from an Api post with this code

componentWillMount() {
fetch('http://url', {
method: 'POST',
body: JSON.stringify({
usuario: 'conosur2',
password: 'test',
})

})
.then((response) => {
console.log(response.json());
})


and im getting this on the console

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}


enter image description here

i need to access that data, how?, i mean, something like
response.json('clientId')
or
response.json().clientId()
, im noob with react yet, so i dont know how promise works or how fetch works (i came from ajax api consume) sorry for my english .

Answer

response.json() returns a promise so you need to resolve it

componentWillMount() {
  fetch('http://url', {
    method: 'POST',
    body: JSON.stringify({
      usuario: 'conosur2',
      password: 'test',
    })

  })
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  })