简体   繁体   中英

Dispatching actions in Redux best practices?

I have a large project I am working on at work and wondering about the proper way to dispatch actions.

In my container for my component I map this function.

const mapDispatchToProps = (dispatch) => {
    return {
        ackMessage:(convo)=> {
        chatSocketService.messageAcknowledge(convo, dispatch);
    }
}

You can see I am passing the dispatch function to my Service.

I need to pass dispatch so in case the socket event fails I can dispatch an error action inside the service.

Is this ok to do? Or would it be better to always keep the dispatching in the containers. If I turned that socket service function into a promise I could do this then but then we may be adding too much logic to the dispatch function in the container?

Is passing the dispatch object around ok to do?

Edit: Here is a snippet of my socket service. On error event from my socket emit I need to dispatch an error:

const chatSocketService = {
      messageAcknowledge(convo, dispatch) {
       const socketConnection = getSocket();
         socketConnection.emit(socketMessages.ACKNOWLEDGE_MESSAGE, {convoID:convo.convoID, msgID:convo.lastMsg.msgID }, 
            (response)=> {
              socketError(response, convo, dispatch);
             });
      }
}

const socketError = (response, convo, dispatch) => {
  if (response.error === CHAT_SESSION_EXPIRE) {
    sessionExpire(dispatch);
  } else if(response.error) {
   dispatch(convoError(convo.convoID, true));
  }
};

const sessionExpire = (dispatch)=> {
  dispatch(disconnectedMessage('Session has expired. Please log out and log back in'));
  dispatch(socketDisconnected(true));
};

Then in my actions.js I have these actions:

export const CONVO_ERROR = 'CHAT_CONVO_ERROR';
export const convoError = (convoID, error) => ({
  type:CONVO_ERROR,
  convoID,
  error
});

export const SOCKET_DISCONNECTED = 'CHAT_SOCKET_DISCONNECTED';
export const socketDisconnected = (disconnected)=> ({
  type:SOCKET_DISCONNECTED,
  disconnected
});

I think you should keep the dispatch function inside the container and separate out the async api call in a different file and import that function to use in this file. Also show us how you are making those async calls like chatSocketSevice using redux-thunk or redux-saga.. I feel like then I could be more helpful.

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