Ilja
Ilja

Reputation: 46479

redux-thunk pass dispatch to another function?

I have current scenario where I want to use function composition:

const funcTwo = (status, response) =>
  (dispatch) => {
    if (response.error) {
      dispatch({ type: TOKEN_FAILURE });
      dispatch(notificationShow('ERROR', response.error.message));
    } else {
      dispatch({ type: TOKEN_SUCCESS, payload: response.id });
    }
  };

export const funcOne = target =>
  (dispatch) => {
    dispatch({ type: TOKEN_REQUEST });
    Helper.createToken(target, funcTwo);
  };

I am currently facing an issue of dispatch not working in funcTwo due to it not being used in any sort of connect() but I wanted to know if it is possible to pass dispatch to it somehow?

Upvotes: 0

Views: 1279

Answers (2)

CharlieBrown
CharlieBrown

Reputation: 4163

Create two functions that are thunks themselves, and move the response handling logic to the first one. Your helper function should return a Promise so you can chain your success / error handlers.

The idea is one thunk can dispatch multiple actions, and any or all of them could be another thunk themselves.

Pseudocode:

export function requestToken(target){
  return (dispatch) => {
     dispatch({ type: TOKEN_REQUEST })
     Helper.createToken(target)
     .then(
        response => {
          dispatch({ 
            type: TOKEN_REQUEST_SUCCESS, 
            payload: response.id
          })
        },
        //your createToken failure handler
        error => {
          dispatch(yourErrorActionCreator(err))
        }
     )
  }

Upvotes: 1

Ashish
Ashish

Reputation: 21

Yes! it is.

const funcTwo = (status, response, dispatch) =>
() => {
    if (response.error) {
      dispatch({ type: TOKEN_FAILURE });
      dispatch(notificationShow('ERROR', response.error.message));
    } else {
      dispatch({ type: TOKEN_SUCCESS, payload: response.id });
    }
  };

export const funcOne = target =>
  (dispatch) => {
    dispatch({ type: TOKEN_REQUEST });
    Helper.createToken(target, (status, response) => funcTwo(status, response, dispatch ));
  };

Upvotes: 0

Related Questions