When I run my frontend and backend, Axios makes a request to the specified route and logs the status of the response to the console. However, even after successful login, the ‘auth’ state does not update. How can I fix this issue?
//PrivateRoute.js
import React, { useState, useEffect } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import axios from 'axios';
const PrivateRoute = () => {
const [auth, setAuth] = useState(false);
useEffect(() => {
const checkAuth = async () => {
try {
const response = await axios.get('/api/users/protected', {withCredentials: true});
console.log('Status: ', response.status)
if (response.status === 200) {
setAuth(true);
}
} catch (error) {
setAuth(false);
}
};
checkAuth();
}, []);
console.log('Auth: ', auth);
return auth ? <Outlet /> : <Navigate to="/" />;
};
export default PrivateRoute;
Status: 200
Auth: false
//Expecting on successfull
Auth: true
//Result
Auth: false
New contributor