0

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?

2 Answers 2

1

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))
        }
     )
  }
Sign up to request clarification or add additional context in comments.

Comments

0

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 ));
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.