Transforming Data

Learn how to Transform data.

In many cases, servers do not return data in the same structure in which we organize it in our state. This means that some API endpoints might require special preprocessing of data before it is sent to the server or special post-processing of the response before it is stored in the state.

The API middleware offers a simple approach to the problem by adding support for transformRequest and transformResponse properties to the action object:

const fixWeirdCommentsAPI = data => {
  // Do some conversion of data
  return data.results.hidden[0].actualData;
};

const fetchComments = () => ({
  type: API,
  payload: {
    url: '/comments',
    onSuccess: setComments,
    transformResponse: fixWeirdCommentsAPI
  }
});

We will usually store a function like fixWeirdCommentsAPI() in a special library and test it separately with the goal of removing it in the future.

Libraries like axios sometimes provide request and response transformations as part of their APIs, which makes supporting this feature virtually effortless:

const {
  url,
  onSuccess,
  onFailure,
  method = 'GET',
  data,
  transformRequest,
  transformResponse
} = action.payload;

const dataProperty = ['GET', 'DELETE'].includes(method) ? 'params' : 'data';

axios.request({
  url,
  method,
  [dataProperty]: data,
  transformRequest,
  transformResponse
})
  .then(response => dispatch(onSuccess(response.data)))
  .catch(error => { /* handle errors */ });

However, if you use low-level browser APIs to make requests, adding data processing is still relatively easy:

const { url, onSuccess, transformResponse } = action.payload;

axios.get(url)
  .then(({ data }) => dispatch(
    onSuccess(transformResponse ? transformResponse(data) : data)
  ));

Get hands-on with 1200+ tech skills courses.