Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  7] [ 5]  / answers: 1 / hits: 27739  / 6 Years ago, sun, october 21, 2018, 12:00:00

I am receiving the error of Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state..



It appears that it is because of this code



const LoginAuth = () => {
navigate(routes.INDEX);
return null;
};


removing navigate(routes.INDEX); stops the error.



What is wrong with the code? Should I be using another method to redirect an authUser? Any help is appreciated.



It is a part of



import React from 'react';
import { navigate } from 'gatsby';

import AuthUserContext from './AuthUserContext';
import withAuthentication from './withAuthentication';

import Layout from './Layout';
import LoginForm from './LoginForm';
import * as routes from '../../constants/routes';

const LoginAuth = () => {
navigate(routes.INDEX);
return null;
};

const LoginPage = () => (
<Layout>
<Transition>
<AuthUserContext.Consumer>
{authUser => (authUser ? <LoginAuth /> : <LoginNonAuth />)}
</AuthUserContext.Consumer>
</Transition>
</Layout>
);

const LoginNonAuth = () => <LoginForm />;

export default withAuthentication(LoginPage);

More From » reactjs

 Answers
-1

Stateless functional components are expected to be pure functions, i.e. contain no side effects, while navigate() provides side effects.



Side effects are supposed to be applied after the component is mounted, that's the purpose of componentDidMount hook.



It should be:



class LoginAuth extends Component {
componentDidMount() {
navigate(routes.INDEX);
}

render() {
return null;
}
}


With the introduction of stateful functional components, side effects belong to useEffect hook:



const LoginAuth = () => {
useEffect(() => {
navigate(routes.INDEX);
}, []);

return null;
};

[#53281] Tuesday, October 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenamackennac

Total Points: 304
Total Questions: 110
Total Answers: 107

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
jenamackennac questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Wed, Apr 21, 21, 00:00, 3 Years ago
Thu, Apr 1, 21, 00:00, 3 Years ago
Tue, Feb 2, 21, 00:00, 3 Years ago
;