I tried a lot of different things and none of them worked. Can you help me?
This is the one I was using just to check if the user has token in storage, It works `
import React, { useState } from "react";
import { Navigate, Outlet } from "react-router-dom";
import Menu from "../components/Menu/Menu";
export default function PrivateRouter() {
const token = localStorage.getItem('token');
return token ? (
<>
<Menu />
<Outlet />
</>
) : (
<Navigate to="/" replace />
);
}
`
This is the code I was trying
`
import React, { useEffect, useState } from "react";
import { Navigate, Outlet } from "react-router-dom";
import { isTokenValid } from "../services/login-service";
export default function PrivateRouterToken() {
const [isValid, setIsValid] = useState(true);
async function tokenAuth() {
const result = await isTokenValid(localStorage.getItem("token"));
if (result.status !== 200) return setIsValid(false);
}
useEffect(() => {
tokenAuth();
}, []);
return isValid ? <Outlet /> : <Navigate to="/" />;
}
`
And this is the validateToken function
`
export async function isTokenValid(token) {
try {
const result = await axios({
method: "POST",
url: `http://xxxxxxxx:3000/validate`,
data: {
token,
},
});
return result
} catch (error) {
return error.response
}
}
`
`
<Route element={<PrivateRouterToken />}>
<Route path="/simulador" element={<Simulator />} />
</Route>
`
I tried wrapping the element with the router, i tried wrapping the route, i tried wrapping the whole routes and nothing worked.