I want to render components based on whether the route passed is in the permissions of a user
but the value of permissions is getting called before it is updated
import { Navigate } from "react-router-dom";
import { useSelector } from "react-redux";
import configService from "../_configService";
import { useEffect, useState } from "react";
function render(c: JSX.Element) {
return c;
}
const ProtectedRoute = (Component: any, route: string) => {
const currentUser: any = useSelector((state) => state);
const [permissions, setPermissions] = useState<string[]>([]);
useEffect(() => {
const config = new configService();
config.loadConfigData().then(() => {
setPermissions(config.Permissions);
});
}, []);
return currentUser && permissions.includes(route)
? render(Component)
: <Navigate to="/" />;
};
export default ProtectedRoute;
>Solution :
As you use .then here so maybe it takes some time for that to complete you can try this in this way by adding loader :
import { Navigate } from "react-router-dom";
import { useSelector } from "react-redux";
import configService from "../_configService";
import { useEffect, useState } from "react";
function render(c: JSX.Element) {
return c;
}
const ProtectedRoute = (Component: any, route: string) => {
const currentUser: any = useSelector((state) => state);
const [permissions, setPermissions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(true); // creating loader state initially it is true
useEffect(() => {
const config = new configService();
config.loadConfigData().then(() => {
setPermissions(config.Permissions);
setIsLoading(false); // when this is processed we will set it false
});
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
return currentUser && permissions.includes(route)
? render(Component)
: <Navigate to="/" />;
};
export default ProtectedRoute;
Explanation : Initially you will see a div with Loading … when the processing in useeffect completed then depending on condition it will go to either ‘/’route or code in render .
Hope this help.