svrcekmichal / redux-axios-middleware

Redux middleware for fetching data with axios HTTP client
MIT License
922 stars 96 forks source link

Incorrect then/catch chain called #103

Closed AdamBCo closed 5 years ago

AdamBCo commented 5 years ago

At the moment, I am using redux-axios-middlware to chain a then/catch on a function from my reducer.

In my reducer, I have the following code:

export function create(data) {
    return {
        types: [CREATE, CREATE_SUCCESS, CREATE_FAILURE],
        payload: {
            request: {
                url: '/api/proposal',
                method: 'POST',
                data
            }
        }
    }
}

In my component, I have the following code:

this.props.create(data)
    .then(() => {
    // router the user away
    console.log("SUCCESS")
})
.catch((response) => {
    //handle form errors
    console.log("ERROR")
})

Unfortunately when the server returns an error, the CREATE_FAILURE action is fired, but it registers as a success in the then/catch chain.

AdamBCo commented 5 years ago

I solved my own issue. If you are using the default configuration you will run into this issue. To fix it, you will have to do the following:

import axios from 'axios'  
import axiosMiddleware from 'redux-axios-middleware'    

const options = {
        // not required, but use-full configuration option
        returnRejectedPromiseOnError: true,
        interceptors: {
            request: [
                ({ getState, dispatch }, config) => {
                   // Request interception
                  return config
                }
            ],
            response: [
            {
              success: ({ dispatch }, response) => {
                // Response interception
                return response
              },
              error: ({ dispatch }, error) => {
                // Response Error Interception 
                return Promise.reject(error)
              }
            }
          ]
        }
}    
export default axiosMiddleware(axios, options)