Javascript api get call returns response but is undefined when chained with .then

I have the following snippet. The api call is successful and the api returns the expected data. However, when I do a console log inside the .then(payload) block and log the payload, it is undefined. Why is this?

return API.get.MyData()        
    .then(response => {
        console.log('response', response);     // this is valid       
        response.json();        
    })        
    .then(payload => {            
        console.log('payload', payload);  // this is undefined... why???    
    }; 

 

Answer

You need to return response.json() to be able to access it in the chained .then

Normally, you do something like this:

fetch(...).then(r => r.json()).then(console.log);

which implicitly returns r.json(), but since you’re using () => { ... }, you need to explicitly return.

return API.get.MyData()        
    .then(response => {
        console.log('response', response);     // this is valid       
        return response.json();        
    })        
    .then(payload => {            
        console.log('payload', payload);  // this is undefined... why???    
    };