fetch response.json() gives responseData = undefined

because you didn't return response.json() in the first then.


Here's how it finally worked out in my case:

fetch('http://localhost:3001/questions', {
        method: 'GET',
        headers: {
        "Accept": "application/json",
        'Content-Type': 'application/json'
        }
    })
    .then(response => { return response.json();})
    .then(responseData => {console.log(responseData); return responseData;})
    .then(data => {this.setState({"questions" : data});})

    .catch(err => {
        console.log("fetch error" + err);
    });
}

Fetch is a little hard to get your head around. I am new to this so dont shoot me down if flames here but response data is another promise and you need to return response data and then handle that promise with yet another then statement where you can finally log the response, also your are missing some return statements in your promises:

var makeRequest = function(){

    fetch('https://jsonplaceholder.typicode.com/posts/1', {
        method: 'get',
        dataType: 'jsonp',
        headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'
        }
    })
    .then((response) => {
       return response.json() // << This is the problem
    })
    .then((responseData) => { // responseData = undefined
        addTestToPage(responseData.title);
        return responseData;
    })
  .catch(function(err) {
      console.log(err);
  })
}

function addTestToPage(textToAdd){
   var para = document.createElement("p");
   var node = document.createTextNode(textToAdd);
   para.appendChild(node);

  var element = document.getElementsByTagName("body")[0];
  element.appendChild(para);
}

makeRequest();

hope that helps see: https://jsfiddle.net/byz17L4L/


The chaining response should look more like this, specifically the response.json part. Then you should get an Object back in console.log.

.then(response => response.json())
.then(response => {

    console.log(response)

}

Tags:

React Native