S
S
Stanislav_Bykov2018-11-15 20:27:52
React
Stanislav_Bykov, 2018-11-15 20:27:52

Why is Warning: Cannot update during an existing state transition (such as within `render`) popping up in the console?

I'm trying to do an authorization check in an app written with React Router v4.
The code looks like this:

...
<Route render={(props) => {requireAuth(props); return <LoggedInLayout/>;}} />
//Перед тем, как перейти на определенный роут, проходит процесс проверки авторизовал ли пользователь или нет
...
function requireAuth(props) {
    if (!SessionStore.isLoggedIn() && props.location.pathname.indexOf('login') === -1) {
        props.history.location.state = {nextPathname: props.location.pathname};
        props.history.replace('/login');
    }
}

When this check is performed, a warning appears in the console:
Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state. react-dom.development.js?61bb:506

Through trial and error, I found out that the line "props.history.replace('/login');"produces this Warning.
Can you please tell me why a warning is shown in the console, and how can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Zharov, 2018-11-15
@Stanislav_Bykov

<Route 
    render={props => isRequireAuth() ? <Redirect to={{pathname: "/login", state: {nextPathname: props.location.pathname}}}/> : <LoggedInLayout/>} 
/>

function isRequireAuth(props) {
    return !SessionStore.isLoggedIn() && props.location.pathname.indexOf('login') === -1
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question