1

I have React-Redux app, and should write a common error handler for all errors returned from the server. Currently for routing I m using 'react-router-dom'. I m using 'withRouter' inside components. But can I redirect inside actions? Or how can this be accomplished?

I saw link How to push to History in React Router v4?. Should I use react-router-redux? Or can this be done with react-router-dom. Could anyone please help?

export function loginDetails(details) {   
return function (dispatch,getState) { 
    gateway.loginUser(details.username, details.password).then(
        response => {
          dispatch({type: AUTH_USER});             
          dispatch(fetchCompanies());              
      },
       error =>{
           handleError(error, dispatch);               
       })
}
}

handleError = (error, dispatch) =>{    
switch(error.response.status){
    case XX: 
        //Want to redirect to '/' here           
        break;
    case YY:    
        //Want to redirect to '/login' here        
        break;
    default:          
        break;
}
}
user8125765
  • 179
  • 1
  • 1
  • 16

1 Answers1

1

what component are you using this in? For example, if someones not logged in, I would just check that with mapStateToProps and if they are not logged in, then import and use react-router-dom's Redirect to send them to the logged in page

Depending on how your store is setup, it may look like:

    const mapStateToProps = state => ({
       loggedIn: state.auth.user !== null
    })

Then your conditional within whatever component you are making the check for

    if(!loggedIn){
      return <Redirect to="/login" />
    }