getting logout on router V6 using <Outlet/> and useEffect to get jwt on refreshing

Viewed 23

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;
1 Answers

In PrivateRoutes.js file,

useEffect(() => {
verify();
}, []);

This will run once after the render, so if you want to that your useEffect is ran when state was null, you need assign value for the array of dependency with following:

useEffect(() => {
    verify();
    }, [something]);

So, every ttime something changes, verify function in useEffect will be called.

However, I think that you should call verify function in Interceptors of axios. I have a example: https://github.com/ImTomQ/react-jwt-auth/blob/develop/src/service/base_service.js

Reference: https://reactjs.org/docs/hooks-reference.html#useeffect

Related