Search code examples
javascriptajaxreactjsfluxreactjs-flux

Javascript fetch API in react-flux


I am studying the flux-react-router-example by @Dan Abramov, I notice in the Fetch API code here: The fetch API has a return promise that has a nested return inside:

return fetch(url).then(response =>
response.json().then(json => {
  const camelizedJson = camelizeKeys(json);
  const nextPageUrl = getNextPageUrl(response) || undefined;

  return {
    ...normalize(camelizedJson, schema),
    nextPageUrl
  };
})

);

I am confused with this nested returns, why is this used here? Why not just return response.json()?

Seems like if I do the same thing, I will get a undefined value


Solution

  • The json retrieved from the response is

    1. converted to camelCase using humps
    2. un-nested using normalizr for easier handling in combination with the redux store
    3. enriched with the next page url, parsed from the link header

    More discussion and reasoning about why storing nested response objects in the store is usually a bad idea can be found at the React JS Google Group.