I
I
Incold2020-07-20 22:45:43
React
Incold, 2020-07-20 22:45:43

Why am I getting a "Maximum update depth exceeded" error?

Hello! After I added a check for an authorized user in the routes, I began to receive an infinite rerender error.
app.js:

function App(props) {

    useEffect(() => props.checkUserToken() , []); // action проверяющий, есть ли JWT в localStorage, если да, то меняет props.isLogin на true
  
    return (
        <div className="d-flex align-items-center justify-content-center">
            <Switch>
                <Route path='/authorization'
                       render={props => !props.isLogin ? <Login {...props} /> : <Redirect to='/main' />}
                />

                <Route path='/main'
                       render={props => props.isLogin ? <MainPage {...props} /> : <Redirect to='/authorization' />}
                />
                <Route
                    render={props => <Redirect to={props.isLogin ? '/main' : '/authorization'} />}
                />
            </Switch>
            {
                props.loading && <Loading />
            }
        </div>
    )
}

Here is what redux-logger outputs:
5f15f170f1225851474654.png
First, the action "CHECK_TOKEN" is called (don't pay attention to persist), which listens to the saga and, depending on the result of the check, calls the action "TOKEN_EXIST", which changes isLogin to true
In theory, then the App should be re-rendered, again "go" to the authorization route and redirect to main there, but an error pops up.
At first, I thought it was about checking the token, so I commented out the hook, logged in again, but everything repeated, the authorization was successful, the data was received, isLogin became true, but this error came up again.
So what is the problem and how to fix this error?
Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Incold, 2020-07-21
@Incold

Found! As always, the mistake is in the little things)

<Route path='/authorization'
                       render={props => !props.isLogin ? <Login {...props} /> : <Redirect to='/main' />}
 />

In such an entry, props.isLogin is taken from the LE (Lexical Environment) function in render, and there it is equal to undefined, so the false condition is constantly fired, and there is an endless redirect from /main to /authorization.
The solution is to change the name of the props parameter to any other name)
Example:
<Route path='/authorization'
                       render={lalala => !props.isLogin ? <Login {...lalala} /> : <Redirect to='/main' />}
 />

H
hzzzzl, 2020-07-20
@hzzzzl

and this exactly happens in the function App, does not write in more detail, in which particular component is update depth exceeded?

L
lnked, 2020-07-21
@lnked

try like this

useEffect(() => props.checkUserToken() , [props.checkUserToken]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question