I use BrowserRouter in my React/Redux app, so I don't create history object nor pass it to BrowserRouter, as it handles its own history. At the moment, I mocked login functionality, and this is function in Login component (which calls login thunk in authActions):
handleSubmit = (e) => {
e.preventDefault();
this.props.authActions.login({
email: this.state.email,
password: this.state.password
});
};
AuthActions are mapped to component props:
function mapDispatchToProps(dispatch) {
return {
authActions: bindActionCreators(authActions, dispatch)
}
}
And this is login thunk in authActions:
export function login(userData) {
return function (dispatch) {
if(userData.email === 'test@test.com' && userData.password === 'pw'){
sessionStorage.setLoggedUser(JSON.stringify(userData));
dispatch(loginSuccess(userData));
this.context.router.history.push('/');
} else {
dispatch(loginFail());
}
}
}
I get error that context is undefined, but after successful Login, app navigates to "/" route. I passed context as second parameter to constructor and super methods in Login component.
class Login extends Component {
constructor(props, context) {
super(props, context);
Now, my question is. What is the best place to do location changes? Component itself, or in actions (thunks)? I mention thunks for purpose, as I will change code and have some async calls to backend. How to access history object when using `BrowserRouter, in both component and actions bound to it?