'Protect routes with React Router v6 and API Call

I am using ReactJS to protect routes, I am using the most current versions, I even use React Router v6, to protect the routes I send a token with jwt to an API where it confirms that the token is valid and that I can access the other routes . The problem is that the axios call occurs after the check in the javascript code and it never gives me a positive result.

App.js

import React, { Component } from "react";
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  Navigate
} from "react-router-dom";

import ReactDOM from "react-dom";
import axios from "axios";

import FormIngreso from "./components/pages/ingreso/FormIngreso";

import Home from "./components/pages/home/Home";

import ProtectedRoutes from "./components/ProtectedRoutes";

export default function App() {

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/ingreso" element={<FormIngreso />} />
        <Route element={<ProtectedRoutes />}>
          <Route path="/" element={<Home/>} />
        </Route>
      </Routes>
    </BrowserRouter>
  );

}

ProtectedRoutes.jsx

import { Navigate, Outlet } from "react-router-dom";
import axios from "axios";

const useAuth = () => {
  var url = window.$url_api + "/acceso/validar";
  var respuesta = false;

  var token = sessionStorage.getItem("react_session");

  if(token) {
    axios.post(url, {"token" : token})
      .then(res => {
        console.log(res);
        console.log(res.data);  
        var estado = res.data.estado;
        if(estado == 200) {
          console.log("noice");
          respuesta = true;
        }     
    }).catch(e => {
        console.log(e);
    });
  }

  return respuesta;
};

const ProtectedRoutes = () => {
  const isAuth = useAuth();
  console.log(isAuth);
  return isAuth ? <Outlet /> : <Navigate to="/ingreso" />;
};

export default ProtectedRoutes;

How do I fix my problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source