infodev
infodev

Reputation: 5235

Run function before dispatch action in mapDispatchToProps in redux

Im my container I would like to make a treatment before dispatch an Action

So first I declared a function

const resumeCallReq = async (call) => {
    const body = { id: call.callId }
    const resCallRes = await resumeCall('queueBaseUrl', body);
    return dispatch(resume(call))
}

Then call it in mapDispatchToProps

const mapDispatchToProps = (dispatch) => ({
    pauseCall: (call) => pauseCallReq(call),
    resumeCall: (call) => resumeCallReq(call),
    endCall: (call) => dispatch(end(call)),
    addNote: (call) => dispatch(addNote(call))
})

I get error

'dispatch' is not defined 

Upvotes: 0

Views: 78

Answers (2)

Mechanic
Mechanic

Reputation: 5380

you can pass dispatch as argument to resumeCallReq

const resumeCallReq = async (call, dispatch) => {
    const body = { id: call.callId }
    const resCallRes = await resumeCall('queueBaseUrl', body);
    return dispatch(resume(call))
}

and in mapDispatchToProps

const mapDispatchToProps = (dispatch) => ({
    pauseCall: (call) => pauseCallReq(call),
    resumeCall: (call) => resumeCallReq(call, dispatch),
    endCall: (call) => dispatch(end(call)),
    addNote: (call) => dispatch(addNote(call))
})

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53934

dispatch not defined within resumeCallReq scope.

There are plenty of ways to get dispatch into scope, one of them is curried function:

const resumeCallReq = (dispatch) => async (call) => {
  const body = { id: call.callId };
  const resCallRes = await resumeCall("queueBaseUrl", body);
  return dispatch(resume(call));
};

const mapDispatchToProps = (dispatch) => ({
  resumeCall: (call) => resumeCallReq(dispatch)(call),
});

Or you can just define the function within mapDispatchToProps:

const mapDispatchToProps = (dispatch) => {
  const resumeCallReq = async (call) => {
    const body = { id: call.callId };
    const resCallRes = await resumeCall("queueBaseUrl", body);
    return dispatch(resume(call));
  };

  return {
    pauseCall: (call) => pauseCallReq(call),
    resumeCall: (call) => resumeCallReq(call),
    endCall: (call) => dispatch(end(call)),
    addNote: (call) => dispatch(addNote(call)),
  };
};

Upvotes: 2

Related Questions