1
\$\begingroup\$

I would like to refactor the fetchRelationships function to use async await. I am not sure what the best way is to do it as this code contains nested .then at response.json().then((json) =>....

Could sby pls post the refactored version?

export const fetchRelationshipsError = (error) => {
  return {
    type: FETCH_RELATIONSHIPS_FAILURE,
    payload: { error }
  };
};

export const fetchRelationshipsRequest = () => {
  return { type: FETCH_RELATIONSHIPS_REQUEST };
};

export const fetchRelationshipsSuccess = (relationships) => {
  return {
    type: FETCH_RELATIONSHIPS_SUCCESS,
    payload: relationships
  };
};

export const fetchRelationships = (url) => {
  return (dispatch) => {
    dispatch(fetchRelationshipsRequest());

    fetch(url, config)
    .then((response) => {
      const responseObj = {
        response: response,
        payload: response.json().then((json) => {
          return { body: json }
        })
      };

      if (!response.ok) {
        const error = new Error(response.statusText);
        responseObj.payload.then((response) => {
          show_error_alert(response.body);
          dispatch(fetchRelationshipsError(response.body));
        });
        throw error;
      }

      return responseObj.payload;
    })
    .then((response) => {
      dispatch(fetchRelationshipsSuccess(response.body))
    })
    .catch((error) => { console.log('Request failed', error); });
  };
};
\$\endgroup\$
1
  • 1
    \$\begingroup\$ We can review this code, but please be aware that responses might not provide the specific rewrite that you requested. \$\endgroup\$ Commented Nov 7, 2017 at 18:28

1 Answer 1

1
\$\begingroup\$

First, I would get that error check out of the way instead of in the middle of the operation. Just throw an error in the middle of the operation and let the catch handle the dispatch.

Also, fetch will always resolve. A common procedure is to use the very first then to evaluate the response and determine how the sequence proceeds. It's usually either resolving with the data or rejecting with the error. But in your case, since both success and error actions dispatch body, the only difference is the action creator. Instead of a resolution/rejection, we just resolve with the correct action based on ok.

export const fetchRelationships = url => {
  return async dispatch => {
    dispatch(fetchRelationshipsRequest())

    fetch(url, config)
      .then(res =>
        // We cannot return res.json() and do its then as part of the
        // outer sequence since we need res. This needs to nest.
        res.json().then(body => 
          res.ok ? fetchRelationshipsSuccess(body) : fetchRelationshipsError(body)))
      .then(action => dispatch(action))
      .catch((error) => dispatch(genericErrorAction())
  }
}

Now for async-await. The returned anonymous function from fetchRelationships will have to be async in order for its body to be able to use await. All promise-returning functions will need to use await. And then turn everything into synchronous-looking code. Here's the same procedure as above, but in async-await form.

export const fetchRelationships = url => {
  return dispatch => {
    dispatch(fetchRelationshipsRequest())

    try {
      const res = await fetch(url, config)
      const body = await res.json()
      const action = res.ok ? fetchRelationshipsSuccess(body) : fetchRelationshipsError(body)
      dispatch(action)
    } catch(error){
      dispatch(genericErrorAction())
    }
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.