0

Hi I am having real difficulty getting a redux thunk action to work as expected in React Native. I have used the exact same method with an application in React which works perfectly, however cannot for the life of me work out why it does not work in my React Native application, throwing an unhandled promise rejection warning, breaking my code.

My login function is as follows:

this.props.loginUser(loginData)
            .catch(err => this.setState({
                errors: err.response.data.errors
            }))

And has been connected to redux as follows:

export default connect(null, {loginUser})(Login)

loginUser function is as follows:

export const userLoggedIn = (user) => ({
    type: LOGGED_IN,
    user
})

const loginUser = (credentials) => (dispatch) =>
    api.user.login(credentials)
        .then(user => dispatch(userLoggedIn(user)))

export default loginUser

And POST request to server:

export default {
    user: {
        login: (credentials) => 
            axios.post('http://10.0.0.103:3000/auth', {credentials})
                .then(user => user.data.credentials)
    }
}

So everything works as expected up until I try to call dispatch with the action. I have included thunk middleware which I assumed would allow all this as per my working React application, however I am getting Unhandled Promise rejection: cannot read property 'data' of undefined in this case, which confuses me.

Thanks for any help in advance

  • Have a look at https://stackoverflow.com/questions/40500490/what-is-an-unhandled-promise-rejection. The `Unhandled Promise` issue is caused by you not having a `catch` on your `axios.post` request. This error message wraps the rest of the error, which is that the `axios.post` returns an `undefined` body. Check that this request is valid, perhaps by making a `curl` request to the server at 10.0.0.103. – A Jar of Clay Aug 31 '18 at 14:07
  • Possible duplicate of [What is an unhandled promise rejection?](https://stackoverflow.com/questions/40500490/what-is-an-unhandled-promise-rejection) – A Jar of Clay Aug 31 '18 at 14:08
  • @AJarofClay, I am slightly confused here as I assumed I could catch errors for the axios post anywhere in the chain which I have done in my login function. The axios request is valid and returns the response I expect every time. Bizarrely updating my action type to a string instead of a constant has fixed everything. No idea why. – Kevin Skeldon Sep 03 '18 at 09:32
  • All promises must have a catch. The MDN docs at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises say "The third mistake is forgetting to terminate chains with catch. Unterminated promise chains lead to uncaught promise rejections in most browsers." – A Jar of Clay Sep 03 '18 at 09:44
  • You could try inspecting the requests sent by your app using the browser Dev Tools, to see whether the correct request is sent. – A Jar of Clay Sep 03 '18 at 09:44

0 Answers0