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

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

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 Report

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 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!