Best place to apply API response transformation [closed]

空扰寡人 提交于 2019-12-24 01:01:42

问题


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.



来源:https://stackoverflow.com/questions/35625791/best-place-to-apply-api-response-transformation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!