I tried to use all the above stated ways but don't know why nothing worked for me.
Finally i solved it and here is my solution to the same:
First make one file of name AdminRoute.js in "routes" folder somewhere in src.
import { Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import { currentAdmin } from "../../functions/auth";
import LoadingToRedirect from "./LoadingToRedirect";
const AdminRoute = ({ children }) => {
const { user } = useSelector((state) => ({
...state,
}));
const [ok, setOk] = useState(false);
useEffect(() => {
if (user && user.token) {
currentAdmin(user.token)
.then((res) => {
console.log("CURRENT ADMIN RES", res);
setOk(true);
})
.catch((err) => {
console.log("ADMIN ROUTE ERR", err);
setOk(false);
});
}
}, [user]);
return ok ? children : <LoadingToRedirect />;
};
export default AdminRoute;
Here you can have your own logic to decide when will user e redirected and when he will not.Like in my case i'm Checking if role of user is admin or not by making one api call.
Then make one LoadingToRedirect.js file in the same "routes" folder.
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
const LoadingToRedirect = () => {
const [count, setCount] = useState(5);
let navigate = useNavigate();
useEffect(() => {
const interval = setInterval(() => {
setCount((currentCount) => --currentCount);
}, 1000);
// redirect once count is equal to 0
count === 0 && navigate("/");
// cleanup
return () => clearInterval(interval);
}, [count, navigate]);
return (
<div className="container p-5 text-center">
<p>Redirecting you in {count} seconds</p>
</div>
);
};
export default LoadingToRedirect;
Now set up your App.js
in your app.js:
Here when you go to '/check' url, the private route functionalities will come in action and it will check if the user is 'admin' or not.Here is the page which is to be protected and it acts as 'children' to
<Routes>
<Route
path="/check"
element={
<AdminRoute>
<Check />
</AdminRoute>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
That's it You are ready to go.
Cheers!!