Use memoization for permission checking

This commit is contained in:
Isaac Wise 2024-02-10 23:40:26 -06:00
parent d5f262200b
commit 44daffbae6

View File

@ -1,15 +1,13 @@
import useAccountStore from "@/store/account"; import useAccountStore from "@/store/account";
import useCollectionStore from "@/store/collections"; import useCollectionStore from "@/store/collections";
import { Member } from "@/types/global"; import { Member } from "@/types/global";
import { useEffect, useState } from "react"; import { useMemo } from "react";
export default function usePermissions(collectionId: number) { export default function usePermissions(collectionId: number) {
const { collections } = useCollectionStore(); const { collections } = useCollectionStore();
const { account } = useAccountStore(); const { account } = useAccountStore();
const [permissions, setPermissions] = useState<Member | true>(); const permissions = useMemo(() => {
useEffect(() => {
const collection = collections.find((e) => e.id === collectionId); const collection = collections.find((e) => e.id === collectionId);
if (collection) { if (collection) {
@ -21,10 +19,11 @@ export default function usePermissions(collectionId: number) {
getPermission?.canCreate === false && getPermission?.canCreate === false &&
getPermission?.canUpdate === false && getPermission?.canUpdate === false &&
getPermission?.canDelete === false getPermission?.canDelete === false
) ) {
getPermission = undefined; getPermission = undefined;
}
setPermissions(account.id === collection.ownerId || getPermission); return account.id === collection.ownerId || getPermission;
} }
}, [account, collections, collectionId]); }, [account, collections, collectionId]);