News for hackers. Stuff that matters.
Re:Simple React Patterns by TekMol on Friday November 10, 2017 @04:06AM (#15668774)

    Then the response body is parsed to JSON
The "res => res.json()" call? But what does this do? res seems to be used nowhere and just discarded without any side effects.
Re:Simple React Patterns by coldtea on Friday November 10, 2017 @07:16AM (#15669380)
If it's a simple statement of this form, the result of the expression is returned.

so res => res.json() is just like having a callback like:

function(res) { return res.json() }

and the next part in the then() chain, takes that result as "planet".

Basically, that last part of the chain, has a signature like:

(function callback(...), function errorCallback(...))

and the callback part gets the result of the previous step as "planet" (if all went ok). If there was an error in the previous steps of the chain, the errorCallback would get called, with the exception passed in as "error".

Re:Simple React Patterns by bfred_it on Friday November 10, 2017 @06:20AM (#15669197)
If it makes it easier to reason about, it's equivalent to:

    // The Promise resolves when the server starts responding
    const response = await fetch(…);
    
    // The Promise resolves when both the transfer and the JSON parsing ended
    const body = await response.json();
So, yes, `response` is only used once and then discarded.

`fetch()` may fool you into thinking that it resolves when the request is complete, but it's always a 2-step operation (unless you start implementing a streaming interface, then it's more than 2 steps)

Re:Simple React Patterns by TekMol on Friday November 10, 2017 @06:24AM (#15669204)
Ah! The equivalent with await seems much clearer to me.
Re:Simple React Patterns by arianvanp on Friday November 10, 2017 @04:10AM (#15668784)
This is a shorthand for

    function (r) { return r.json()}
Note the extra return. We return the JSON decoded response that is our planet. and use its value to set state if no error occured
Re:Simple React Patterns by TekMol on Friday November 10, 2017 @06:23AM (#15669201)
Got it! Thanks!
Re:Simple React Patterns by shamas on Friday November 10, 2017 @08:09AM (#15669589)
This is pretty straightforward es6. The difference between =>{} and just => is confusing at first. One is a function body and the other is an implied return statement.
Re:Simple React Patterns by stevula on Friday November 10, 2017 @04:13AM (#15668790)
`res.json()` is the return value of the first `then` block, which is then passed to the second `then` block as `planet` (if json parsing doesn't throw an error).
Re:Simple React Patterns by pgkl on Friday November 10, 2017 @05:13AM (#15668978)
res => res.json() returns the result of res.json()

That function is thenable so following it .then is called and the result or error is passed to the first or second function respectively.