I have to do a users/permissions table in which "Permissions" is the X axis and "Users" the Y axis. Rest of the table is populated with checkboxes that indicates if X User has Y Permission. Both of these are dynamic length, and each API has some kind of access to the other one. Ie: Permissions API has for each Permission, an array of Users that have that permission. And viceversa, Users API has for each User, an array of Permissions that the User has.
I am having problem with nested maps and I feel that it's expensive to do it like this? (If there is 40 permissions and 350 users, we talk about 14k checkboxes)
How do I save state for each checkbox? It's ok what I'm trying to do with the checks useState? I also need a way to send updated permissions to another API.
Using the "isChecked" const inside the return statement, I am forcing the checkbox to only be true or false and I can't change that when on click.
At return statement, I should be mapping "checks" but for some reason is not being populated as I am expecting to.
[{ userID: number, permID: number, checked: boolean }, { userID: number, permID: number, checked: boolean }, etc ]
Code looks something like this:
const [checks, setChecks] = useState([]);
const users = //GET to users API
const permissions = //GET to permissions API
const mapPermissions = () => {
users.map((user: any) => {
permissions.map((permission: any) => {
setChecks((prevState: any) => [
...prevState,
{
userID: user.id,
permID: permission.id,
//group_lists is an array of Permissions ID that current user has.
checked: user.group_lists ? user.group_lists.includes(permission.id) : false,
},
]);
});
});
};
useEffect(() => {
mapPermissions();
}, []);
return (
<TableContainer component={Paper}>
<Table className={styles.table}>
<TableHead>
<TableRow>
<TableCell className={styles.blank} />
{permissions.map((permission) => (
<TableCell key={permission.id} className={styles.header}>
{permission.name}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
// Should be replacing this for "checks" state map.
{users.map((user: any) => (
<TableRow key={user.id}>
<TableCell
className={styles.left}
>{`${user.first_name} ${user.last_name} (${user.username})`}</TableCell>
{permissions.map((permission: any) => {
const isChecked = user.group_lists
? user.group_lists.includes(permission.id)
: false;
return (
<TableCell key={`${user.id}-${permission.id}`}>
<input
type="checkbox"
checked={isChecked}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
console.log({
user: user.id,
permid: permission.id,
currentState: isChecked,
futureState: e.target.checked,
});
}}
/>
</TableCell>
);
})}
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
I am open to delete everything if needed. Thanks in advance :)