Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to render component with updated value of constant using async function in ReactJS

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading