0

I have App.js only contains route:

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route element={<Login />} path="/login"></Route>
        <Route element={<NotFound />} path="*"></Route>
        <Route element={<PrivateRoutes />}>
          <Route element={<Home />} path="/"></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

And my PrivateRoute.js is

function PrivateRoutes() {
    const key = sessionStorage.getItem("key")
    // I would like to use Axios here to verify if the token is legal
    return (
        key === "123" ? <Outlet /> : <Navigate to="/login"></Navigate>
    )
}

I would like to use Axios to verify if the token is legal, but Axios is asynchronous, so I can not get response and compare with local token.

What should I do ?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

1

You can make an async/await function of your PrivateRoutes :

function PrivateRoutes() {
  const [component, setComponent] = React.useState(null);

  const key = sessionStorage.getItem("key");

  async function getData() {
    await axios.get('/verify-token', {
      params: {
        token: key
      }
    }).then(response => {
      if (response.data.valid) {
        setComponent(<Outlet />);
      } else {
        setComponent(<Navigate to="/login"></Navigate>);
      }
    }).catch(error => {
      console.error(error);
    });
  }

  React.useEffect(() => {
   getData();
  }, []);

  return component;
}
Johan
  • 2,088
  • 2
  • 9
  • 37