i think i'm missing some theory here cause i cant get the axios call that verifies jwt token to happen before the auth state goes back to its initial state which is null, therefore page logouts on refreshing. i know axios is asynchronous but returning <outlet/ > and <navigate/ > within the verify function returns nothing.
PrivateRoutes.js
const PrivateRoutes = () => {
const { auth, setAuth } = useContext(AuthContext); // authentication state
const verify = async () => {
Axios.defaults.withCredentials = true;
const res = await Axios.get("http://localhost:3001/verify");
const data = res.data;
console.log("data from jwt", data);
setAuth({
logged: data.logged,
id: data.user_id,
name: data.name,
});
};
useEffect(() => {
verify();
}, []);
console.log("private", auth);
return auth.logged ? <Outlet /> : <Navigate to="/login" />;
};
export default PrivateRoutes;
on console i get this order on refreshing.
console
private {logged: null, name: '', id: ''}
data from jwt {id: 3, name: 'mariela', logged: true}
i tried this but it renders nothing
const PrivateRoutes = () => {
const { auth, setAuth } = useContext(AuthContext);
const verify = async () => {
Axios.defaults.withCredentials = true;
const res = await Axios.get("http://localhost:3001/verify");
const data = res.data;
setAuth({
logged: data.logged,
id: data.usu_id,
name: data.nombre,
});
if (data.logged) {
return <Outlet />;
} else {
return <Navigate to="/login" />;
}
};
useEffect(() => {
verify();
}, []);
};
export default PrivateRoutes;