A Store of Actions for optimistic updates is a good approach in Redux/Flux?

徘徊边缘 提交于 2019-12-02 20:37:25

To the future readers who might be a little bewildered: we don't call these functions “stores” anymore: we call them reducers. So the question is about a reducer remembering actions.

Personally I don't like the approach you're suggesting there. You're putting logic into actions and using inheritance for this. On the contrary, Redux prescribes actions to be plain objects without logic. They shouldn't “know” how to update some state, and they shouldn't hold it—instead, they should describe what happened.

I think the approach for implementing optimistic updates in Redux is similar to how you'd implement Undo in Redux, which in turn is inspired by Elm architecture. The idea is that you should write a function that takes a reducer (and some options) and returns a reducer:

function optimistic(reducer) {
  return function (state, action) {
    // do something?
    return reducer(state, action);
  }
}

You'd use it just like a normal reducer:

export default combineReducers({
  something: optimistic(something) // wrap "something" reducer
})

Right now it just passes the state and action to the reducer it wraps, but it can also “remember” actions:

function optimistic(reducer) {
  return function (state = { history: [] }, action) {
    // do something with history?
    return {
      history: [...state.history, action],
      present: reducer(state.history[state.history.length - 1], action)
    };
  }
}

Now it accumulates all actions in the history field.

Again, this by itself is not very useful, but you can probably see how you can implement such higher order reducer that:

  • keeps track of pending async actions by their IDs and starts recording the history when it sees an action with status: 'request';
  • when it receives an action with status: 'done', resets the history;
  • when it receives an action with status: 'fail', adjusts the history to not include the initial action with status: 'request' and re-runs the reducer to re-calculate the present state as if the request never happened.

Of course I haven't provided the implementation, but this should give you an idea of how to implement optimistic updates in a Redux way.

Update: as per the OP's comment, redux-optimist seems to do exactly that.

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