Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
How to implement roles if user have more than one roles in Reactjs?

Previously I've created with Custom Hook and it works but only for 1 role .

How do I make it work for users who have more than 1 role?

example of user roles:

  • User 1 = ["Super Admin", "Marketing"]
  • User 2 = ["Marketing", "Customer Service"]

This code for Role Map:

enum ROLES {
  SUPER = "Super Admin",
  MARKETING = "Marketing",
  CUSTOMER_SERVICE = "Customer Service"
};

export const rolesMaps = (role) => {
  switch (role) {
    case ROLES.SUPER_ADMIN: {
      return {
        adminUserFeature: "READ WRITE DELETE",
        homePageFeature: "READ WRITE DELETE",
      };
    }
    case ROLES.MARKETING : {
      return {
        adminUserFeature: "READ WRITE DELETE",
        homePageFeature: "READ WRITE ",
      };
    }
    case ROLES.CUSTOMER_SERVICE : {
      return {
        adminUserFeature: "READ",
        homePageFeature: "READ",
      };
    }
    default:
      return {};
  }
}

This code for Custom Hook

import { useMemo } from "react";
import { rolesMaps } from "./rolesMaps"; //Role Map

export const usePermissions = (role, feature) => {
  return useMemo(() => {
    const permissions = rolesMaps(role && role[0])[feature];
    console.log("permisi", permissions);
    
    return {
      canRead: !!permissions?.includes("READ"),
      canWrite: !!permissions?.includes("WRITE"),
      canDelete: !!permissions?.includes("DELETE"),
    };
  }, [role, feature]);
}

This code for implement on component

  const role = useGetRole()
  const { canWrite } = usePermissions(role, "homePageFeature");

  {canWrite && <Button variant="primary" onClick={handleAddNew}>Add New</Button>}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

For your role map, you could switch to using a key value pair where the value is an array of strings. This way you can check for duplicates easier, Here is my implementation.

enum ROLES {
    SUPER_ADMIN = "Super Admin",
    MARKETING = "Marketing",
    CUSTOMER_SERVICE = "Customer Service"
};

// you can now pass in multiple roles into ROLES
export const rolesMaps = (roles: ROLES[]) => {
    const permissions: {[key: string]: string[]} = {};

    const addPermission = (featureName: string, permissionsToAdd: string[]) => {
        if (permissions[featureName] === undefined) {
            permissions[featureName] = [];
        }

        for (const perm of permissionsToAdd) {
            if (permissions[featureName].indexOf(perm) === -1) {
                permissions[featureName].push(perm);
            }
        }
    }

    for (const role of roles) {
        switch (role) {
            case ROLES.MARKETING:
            case ROLES.SUPER_ADMIN: {
                // add permissions that both marketing and super_admin share
                addPermission("adminUserFeature", ["READ", "WRITE", "DELETE"]);
                addPermission("homePageFeature", ["READ", "WRITE"]);
                
                if (role === ROLES.SUPER_ADMIN) {
                    // only admin role can delete in the homePageFeature
                    addPermission("homePageFeature", ["DELETE"]);
                }
            }
            case ROLES.CUSTOMER_SERVICE : {
                addPermission("adminUserFeature", ["READ"]);
                addPermission("homePageFeature", ["READ"]);
            }
        }
    }

    // the return value is now a {[key: string]: string[]}, the value is an array of strings
    // If you want the value to still be the same syntax as in your question
    // You can use permissions[featureName].join(" ") to get a string of roles seperated by a space
    // But the current usage of the return value should still work as arrays also have the .include() method
    return permissions;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I have used liked this

export const useRole = ([allowedRoles]) => {
    const { user } = useAuth()
    const history = useHistory()
    useEffect(() => {
        return () => {
            if (!allowedRoles.includes(user?.role)) {
                history.push('/error')
            }
        }
    }, [])

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda