Best place to apply API response transformation [c

2019-07-12 15:54发布

问题:

In an async action creator, I fetch data from the server. The data is not very well formatted for my use case and I need to transform it to use it in the UI.

Question : should I

  1. Transform data just after it arrives before dispatching a success action with the transformed data ?

    fetch("some/url")
    .then(res => dispatch(successActionCreator(transform(res)))
    
  2. Dispatch a success action with raw data and store it as, and transform it inside mapStateToProps ?

  3. Dispatch a success action with raw data and transform it in the reducer ?

In 1., the data will be transformed when I need it, and it seems to me that it decouples the API data format and my Redux store. But the transform logic is in the data fetching action.

In 2., the async action creator stays simple with no logic at all and the mapping happens at the UI layer. But it means that I'll need to optimise it with something like reselect since mapStateToProps is called for each render.

In 3., the async action creator stays simple with no logic at all but the action is coupled to the API data format.

I'm going for 1. (and unit-test the transform anyway), but I'm not completely happy. Any suggestion ? Thanks !

-- Edit : since the question is subject to an opinionated answer, I'm kinda answering my self here. I'll go with 1., for all the reasons stated in the comments and one of the answer.

回答1:

Option 1 is the correct answer.

If you pass around raw server responses you are coupling your client to the server side implementation. Isolating these sorts of transformations is important for the future maintainability of the application.