Sarasota Sun Sarasota Sun - 1 year ago 101
React JSX Question

ReactJs - Warning when transitioning off page after successful login

I have a straight foward login page which calls an api service to verify user login:


state => ({user: state.auth.user}),
class Login extends React.Component {


_handleSubmit = (event) => {
this.props.login({username: username.value, password: password.value},
(result) => {
return result;

render() {
const {user, logout} = this.props;
return (
!user ?
... Show login page with submit button .....

: this.context.router.replace('/')

While the component works as intended, I am receiving the warning:

Cannot update during an existing state transition (such as within
or another component's constructor). Render methods should be
a pure function of props and state; constructor side-effects are an
anti-pattern, but can be moved to

I know the warning is due to the replace state of the router, but I do not know what would be the best way to prevent this warning and still accomplish the goal of moving away from the login page if the User exists.

Any ideas?


Abdud Dayan Adeeb had the solution .....

componentWillReceiveProps(nextProps ) {
if (nextProps.user) this.context.router.replace('/')

Answer Source

The problem I see here is you are trying to attempt a transition when the component is rendering/updating.

The best thing to do would be to move the transition logic to the componenetWillReceiveProps function of your component

componenentWillReceiveProps(nextProps) {
    if (nextProps.user) this.context.router.replace('/')