Matt Saunders
Matt Saunders

Reputation: 4371

Can't return response from redux-thunk

I'm calling an action from a component:

this.props.createWebsite(this.state)

This calls an action and passes in some state. The action looks like this:

export const createWebsite = data => {
  return (dispatch, getState) => {
    return axios.post(
        API.path + 'website/', 
        {
            // some data
        }
    )
    .then(response => {

    })
    .catch(error => {

    })
  }
}

I want to handle the response and error in the component that called this, rather than in the action itself. How can I do this? I have tried:

this.props.createWebsite(this.state).then(response => { /**/ }).catch(error => { /**/ })

This sort of works but it doesn't catch errors.

Upvotes: 1

Views: 325

Answers (1)

Julien TASSIN
Julien TASSIN

Reputation: 5212

You need to remove the catch from the createWebsite declaration.

It handle the error and to not propagate it. So the error is lost. To get it :

remove the catch

export const createWebsite = data => {
  return (dispatch, getState) => {
    return axios.post(
        API.path + 'website/', 
        {
            // some data
        }
    )
    .then(response => {
      return response;    
    })
  }
}

rethrow the exception

export const createWebsite = data => {
  return (dispatch, getState) => {
    return axios.post(
        API.path + 'website/', 
        {
            // some data
        }
    )
    .then(response => {
      return response;
    })
    .catch(error => {
      // Do something
      throw error;
    })
  }
}

Upvotes: 1

Related Questions