Blossom
Blossom

Reputation: 123

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.

Upvotes: 3

Views: 1126

Answers (3)

Ryan Wheale
Ryan Wheale

Reputation: 28430

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

Upvotes: 5

Evert
Evert

Reputation: 99717

This:

() => 5

is equal to

() => { return 5; }

If you use curly braces, you need to explicitly return.

Upvotes: 1

rigojr
rigojr

Reputation: 361

you have to return something when you are using {} in an arrow function, let's take a look.

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

Read this MDN doc.

Upvotes: 1

Related Questions