Search code examples
reactjses6-promisefetch-apicurly-braces

Why Curly braces while handling a Promise object provides undefined data?


In a simple React App that fetch response from a API, the following code with curly braces has resulting data value as undefined.

fetch('http://localhost:8000/track/?id='+this.state.input)
            .then(res => {res.json()})        //Note Curly braces around {res.json()}
            .then((data) => {
                console.log(data);  

Whereas when curly braces was removed, surprisingly it fetched and printed the response data in the console.

fetch('http://localhost:8000/track/?id='+this.state.input)
            .then(res => res.json())         //No Curly braces - then works fine
            .then((data) => {
                console.log(data);

What is the reason for this behavior with curly braces around a Promise function? Is it not possible to use curly braces ?Why? Promises are slightly confusing though.


Solution

  • When you are using an arrow function, you can omit the curly braces for very simple functions. This will implicitly return the result of the expression following the arrow. This is best explained by example. Let's start with a simple function:

    var foo = () => {
      return 'bar';
    }
    

    This can be shortened to this one liner:

    var foo = () => { return 'bar' }
    

    Which can be further shortened to this (removed curly braces and return statement):

    var foo = () => 'bar';
    

    In your case, you can think of the code you posted like this:

    .then(res => {
      res.json()
    })
    

    The above function doesn't return anything, which is the source of your problem. What your really want is this:

    .then(res => {
      return res.json()
    })
    

    Which can be shortened like this:

    .then(res => { return res.json() }) // one-liner with curlys
    .then(res => res.json())            // without curlys