Skip to content

Latest commit

 

History

History
52 lines (36 loc) · 1.43 KB

react.usecerbos.md

File metadata and controls

52 lines (36 loc) · 1.43 KB

Home > @cerbos/react > useCerbos

useCerbos() function

A hook to access the Cerbos client passed down by the CerbosProvider().

Signature:

export declare function useCerbos(): ClientWithPrincipal;

Returns:

ClientWithPrincipal

Remarks

The client's methods are asynchronous, so depending on your use case it may be easier to use one of the higher-level hooks (useCheckResource(), useCheckResources(), or useIsAllowed()), which convert the resulting promises into AsyncResults.

Example

import { useCerbos } from "@cerbos/react";

function SomeComponent() {
  const cerbos = useCerbos();

  const handleClick = async () => {
    const decision = await cerbos.checkResource({
      resource: {
        kind: "document",
        id: "1",
        attr: { owner: "[email protected]" },
      },
      actions: ["view", "edit"],
    });

    if (decision.allAllowed()) {
      // do something
    } else if (decision.allowedActions().includes("view")) {
      // do something else
    }
    ...
  };

  return <button onClick={handleClick}>...</button>;
}