'Cannot update a component (`BrowserRouter`) while rendering a different component (`Login`)
I am getting this warning when I have worked on my react project:
Warning: Cannot update a component (
BrowserRouter) while rendering a different component (Login). To locate the bad setState() call insideLogin
My Code:
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
);
reportWebVitals();
Specific part of the code from Login.js:
if (accessToken) {
navigate(from, { replace: true });
}
This specific part of code triggers this warning. When I navigate from the login page to another page after logging in, it shows this warning.
Solution 1:[1]
It has to be wrapped in an effect so that it runs after it rendered, not during the render phase.
function MyComponent() {
React.useEffect(() => {
if (accessToken) {
navigate(from, { replace: true });
}
}, [])
return (<div>{/* ... */}</div>)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silviu-Marian |
