Fredo
Fredo

Reputation: 13

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?

Upvotes: 0

Views: 3151

Answers (1)

guiwme5
guiwme5

Reputation: 822

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

//now useAuth is not a function anymore is a hook (leaves in the component lifecycle).
const useAuth = () => { 
  const [isAuth, setIsAuth] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      var token = sessionStorage.getItem("react_session");
      var url = window.$url_api + "/acceso/validar";

      if(!token) setIsAuth(false);

      try {
        const res = await axios.post(url, {"token" : token})
        console.log(res);    
        setIsAuth(false);

        if(estado == 200) {
          console.log("noice");
          setIsAuth(true);
        }     
      }
      catch(e) {
        console.log(e);
        setIsAuth(false);
      }
    };          

   };
   fetchData();
 }, []);      

  return isAuth;
};


const ProtectedRoutes = () => {
  const isAuth = useAuth();

  if (isAuth === null) // waiting..
    return null;

  return isAuth ? <Outlet /> : <Navigate to="/ingreso" />;
};


export default ProtectedRoutes;

Upvotes: 6

Related Questions