简体   繁体   中英

Error handling with redux-thunk, react native

I am using a redux setup in my react-native app using redux-thunk. this is the simple login action

export const doLogin=(request, onSuccess, onError)=>{
return dispatch=>{
    console.log(request)
    axios.post(`/AppUser/LoginValidation`, request).then(res=>{
        console.log(res.data)
        if(res.data.isSuccess=== true){
            dispatch({
                type:LOGIN,
                payload:{
                     auth_token: res.data.authToken,
                     responseResult: res.data.responseResult,
                     loggedIn: true
                }
            })
            onSuccess && onSuccess();
        }else{
            dispatch({
                type: ERROR,
                payload: res.data.message
            })
            onError && onError();
        }
    })
    .catch(err=>{
        console.log('err',err )
    })
}

}

and this way i have used above code in front end:

 props.doLogin(data,()=>{
        action.setErrors({password: props.errorMsg})
        // action.resetForm();
        // setMobileno(null)
        props.navigation.navigate('FLayout', { screen:'Home' })
    })

it redirects me if the login id and password are proper. if I put the invalid id and password, it still redirects me to the home page instead of showing me a message.

It looks like you aren't passing the callback method to handle errors. Try this:

const onSuccess = () => {
  props.navigation.navigate('FLayout', { screen:'Home' })
}

const onError = () => {
  action.setErrors({password: props.errorMsg})
  // action.resetForm();
  // setMobileno(null)
}

props.doLogin(data, onSuccess, onError)

I found a solution in another way, I have to write two callback in my front-end app section, like,

props.doLogin(data,()=>{
    
    // action.resetForm();
    // setMobileno(null)
    props.navigation.navigate('FLayout', { screen:'Home' })
},
()=>{
    action.setErrors({password: props.errorMsg})
    console.log("another callback for error handle")
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM