Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
¿Cómo implementar roles si el usuario tiene más de un rol en Reactjs?

Previamente he creado con Custom Hook y funciona pero solo para 1 rol.

¿Cómo hago que funcione para los usuarios que tienen más de 1 rol?

ejemplo de roles de usuario :

  • Usuario 1 = ["Superadministrador", "Marketing"]
  • Usuario 2 = ["Marketing", "Servicio al cliente"]

Este código para el mapa de roles:

 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 {}; } }

Este código para 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]); }

Este código para implementar en el componente

 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 answers
Answer question

0

Para su mapa de roles, puede cambiar a usar un par de valores clave donde el valor es una matriz de cadenas. De esta manera, puede verificar si hay duplicados más fácilmente. Aquí está mi implementación.

 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 Report

0

He usado me gusta esto

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!