Adee
Adee

Reputation: 377

How to capture a response from redux-api-middleware

My action:

const someAction = () => {
  return {
    [RSAA]: {
      types: [
        SOME_REQUEST,
        SOME_SUCCESS,
        SOME_FAILURE,
      ],
      endpoint: ...,
      method: 'POST',
    }
  };
};

I call it in the following way:

this.props.someAction();

Everything works correctly, I am able to handle data in the reducer. The question is, can I somehow pick up the result of the function when it is called?

I mean something like that:

this.props.someAction().then( //success ).catch( //error );

Upvotes: 1

Views: 1060

Answers (1)

peter.schindler
peter.schindler

Reputation: 11

Putting it simply, redux-api-middleware goes through the following steps (more details here):

  1. Dispatches SOME_REQUEST action
  2. Makes POST request to your endpoint
  3. If request is successful, it dispatches SOME_SUCCESS action, otherwise it dispatches SOME_FAILURE

The result response you are looking for can be picked up in your Reducer by accessing:

action.payload

So the Reducer where you will handle success or failure will look somewhat like this:

export default (state=initialState, action) => {

  switch(action.type) {

    case SOME_SUCCESS:
      let success_response = action.payload
      // some logic handling successful response
      // return modified state

    case SOME_FAILURE:
      let error_response = action.payload
      // some logic handling error message response
      // return modified state

    default:
      return state;
  }
}

Upvotes: 1

Related Questions