I've created a context named AuthContext
in my react
app.
export const AuthContext = createContext({
isLoggedIn: false,
login: (userid)=>{},
logout: ()=>{}
})
And here's the code of my App.js
file
function App() {
let [isLoggedIn, setIsLoggedIn] = useState(false);
const login = useCallback((id) => {
setIsLoggedIn(true);
}, []);
const logout = useCallback(() => {
setIsLoggedIn(false);
}, []);
let routes = (
<Routes>
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Navigate to="/login" />}></Route>
</Routes>
);
if (isLoggedIn) {
routes = (
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/trends" element={<Trends />} />
<Route path="/reports" element={<Reports />} />
<Route path="/summary" element={<Summary />} />
<Route path="/logout" element={<Logout />} />
<Route path="*" element={<Navigate to="/dashboard" />}></Route>
</Routes>
);
}
return (
<>
<AuthContext.Provider
value={{ isLoggedIn, login: login, logout: logout }}
>
<Router>
<Navigator />
{routes}
</Router>
</AuthContext.Provider>
</>
);
}
After login, I want to set the isLoggedIn
state true
. To do that, in my Login.js
file, this is what I did:
export default function Login() {
let loginURL = "******"
const auth = useContext(AuthContext);
const [lg] = useLogin();
const handleLogin= async () => {
const response = await lg.login(loginURL);
console.log(response);
auth.login(responsel.id) //defined in the App.js file. (Mentioned above)
};
return (
<>
<button
type="button"
onClick={handleLogin}
>
Login
</button>
</>
);
}
I get the response properly in handleLogin
function. After that, I call the auth.login
function from the context to set the state isLoggedIn
to true
but then I get this warning:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
And this happens infinitely and don't let any other things to load on the screen