I have a login form and when I click login, the URL is updated but the component is not. (e.g. localhost:8080/somewhere but still on login page)
The versions of my packages are as follows:
This is the Login component
class Login extends React.Component {
handleFormSubmit = ( values ) => {
this.props.signInUser(values);
history.push('/somewhere');
};
<div>
<div>
<h2>Log In</h2>
<form onSubmit={ this.props.handleSubmit( this.handleFormSubmit ) }>
<Field name="email" type="text" label="Email"/>
<Field name="password" type="password" label="Password"/>
<button action="submit">Sign In</button>
</form>
</div>
</div>
...
}
export default connect( mapStateToProps, Actions, )( reduxForm({
form: 'login',
validate,})( Login ));
I am using history.push because I have a shared history object.
My routes are as follows:
<Provider store={ store }>
<Router history={history}>
< App >
<Switch>
<Route exact path="/" component={ Home }/>
<Route path="/login" component={ Login } />
<Route path="/somewhere" component={ Somewhere } />
</Switch>
</ App >
</Router>
</Provider>
I tried using <Redirect>
but can't get it to work. Also tried using withRouter
but discovered this is only applicable for components not declared in the routes.
How do I redirect to the Somewhere component when submitting the form?
I'm not sure that this is the best way to do this, but it works for me :
<form onSubmit={ this.props.handleSubmit( this.handleFormSubmit ) }>
<Field name="email" type="text" label="Email"/>
<Field name="password" type="password" label="Password"/>
<button action="submit">Sign In</button>
{this.props.user.loggedIn && <Redirect to={'/Somewhere'} />}
</form>
Given the fact that this.props.handleSubmit( this.handleFormSubmit )
dispatches an action who toggles to true the loggedIn
prop of user
.
You have to map user
to props, for your component to re-render when user.loggedIn
is changed. The <Redirect>
will then be activated.