usePermissions()

Remarks

Observe security permissions for a table and individual objects managed by Dexie Cloud. Use this hook in order to know whether to render certain action buttons depending on what permission the user has to modify the object or add / remove objects.

Dependencies

npm i react dexie dexie-cloud-addon dexie-react-hooks

or

yarn add react dexie dexie-cloud-addon dexie-react-hooks

Syntax

export function usePermissions<T>(
  db: Dexie,
  table: string | Table,
  obj: T
): PermissionChecker<T>;

export function usePermissions<T extends DexieCloudEntity>(
  entity: T
): PermissionChecker<T>;

export interface PermissionChecker<T> {
  add(...tableNames: string[]): boolean;
  update(...props: string[]): boolean;
  delete(): boolean;
}
Parameter Description
db A Dexie instance with dexie-cloud addon active
table A table name or Table instance
obj An object retrieved from a dexie query
entity If your table is declared using DexieCloudTable using a Entity-derive class mapped to the table using mapToClass(), as examplified in declaration of the TodoList class declared in dexie-cloud-todo-app, you only need to provide a single argument - the entity itself

Sample

See dexie-cloud-todo-app’s TodoListView.tsx, TodoItemView.tsx and TodoDB.ts

interface Props {
  // todoList prop comes from query
  // result in parent component.
  todoList: TodoList;
}

function MyComponent({ todoList }: Props) {
  // Get the PermissionChecker into a local variable 'can' to be
  // used in the JSX later on:
  const can = usePermissions(db, "todoLists", todoList);

  // Retrieve the todo-items
  const items = useLiveQuery(
    () => db.todoItems.where({ todoListId: todoList.id }).toArray(),
    [todoList.id]
  );

  //
  // Actions
  //

  function editTitle() {
    // ...launch a dialog to edit title
  }
  function addNewItem() {
    // ...launch a dialog to add a new todo-item
  }
  function deleteList() {
    return db.transaction(
      "rw",
      [db.todoLists, db.todoItems, db.realms, db.members],
      () => {
        // Delete all related data:
        db.todoItems.where({ todoListId: todoList.id }).delete();
        db.todoLists.delete(todoList.id);
        const tiedRealmId = getTiedRealmId(todoList.id);
        db.members.where({ realmId: tiedRealmId }).delete();
        db.realms.delete(tiedRealmId);
      }
    );
  }

  //
  // JSX part:
  //
  return (
    <>
      Title: {todoList.title}{" "}
      {can.update("title") && <button onClick={editTitle}>Edit title</button>}
      <button disabled={!can.delete()} onClick={deleteList}>
        Delete list
      </button>
      <ul>
        {items?.map((item) => (
          <li key={item.id}>
            <TodoItem item={item} />
          </li>
        ))}
      </ul>
      {can.add("todoItems") && <button onClick={addNewItem}>Add new item</button>}
    </>
  );
}

Table of Contents