简体   繁体   中英

Good pattern for redux action in callback

Supposing I have an update comment action. When a user updates comment after getting a successful result from Promise I should close comment editor. This is my sample code from my project:

export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}

In react component I use action like the following code:

handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}

It works well but I think is not a good pattern to close comment editor. I'm looking a correct pattern to close editor without passing callBack like I did if any.

The only thing that updates your application's state is your reducers.

The reducer should be responsible to update the state of your application and not your action (you are now passing getState).

I suggest you to look at redux-promise-middleware

The middleware enables optimistic updates and dispatches pending, fulfilled and rejected actions, which can be intercepted by the reducer.

When you are using redux-thunk , you can dispatch an action from another action. What you can do is that, commentEditor have a state which you store in redux and based on that state open or close the commentEditor

export const updateComment = (comment, comment_id) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             dispatch({type: 'CLOSE_COMMENT_EDITOR', id: comment_id})
       })
    }
}

After this in a reducer on this action change the state of redux store, something like

import update from 'immutability-helper'


var initialState = [{commentId: '1', commentEditorOpenStatus: false}, {commentId: '2', commentEditorOpenStatus: false}]
const reducer = (state = initialState, action) => {
     switch(action.type) {
         'CLOSE_COMMENT_EDITOR': 
                  const idx = state.findIndex(obj => obj.commentId == action.id);
                  return update(state, {
                         [idx]: {
                              commentEditorOpenStatus: {
                                  $set: false
                               }
                          }
                   })
            // Other action handlers here
            default: return state
     }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM