SafeFn
Running a SafeFn

useServerAction hook

npm i safe-fn-react

The useServerAction() hook makes calling a SafeFn from the client easy. It handles transitioning, exposes loading states and converts the Promise<ActionResult> object back into a ResultAsync.

server/... .ts
const mySafeFn = SafeFn.new().handler(() => {
  return ok("Success");
});
server/... .ts
const myAction = mySafeFn.createAction();
client/... .tsx
const { execute, result, isPending, isSuccess } = useServerAction(
  action,
  callbacks,
);

Arguments

SafeFn Action

The action argument is the resulting function from calling createAction() on a SafeFn.

Callbacks

The useServerAction() hook optionally takes in the following callbacks functions that will run on the client, and the properties of the argument object they can take:

  • onStart() - Called when execute() is called.
    • unsafeRawInput: The raw input passed into execute().
  • onSuccess() - Called when the execute() returns an Ok.
    • unsafeRawInput: The raw input passed into execute().
    • value: The value returned from the action. See here for the type.
  • onError() - Called when the execute() returns an Err.
    • unsafeRawInput: The raw input passed into execute().
    • error: the error returned from the action. See here for the type.
  • onComplete() - Called when the execute() returns.
    • unsafeRawInput: The raw input passed into execute().
    • result: The result returned from the action. See here for the type.

These callbacks are not awaited. This means onStart() does not block the action from running, and the other callbacks do not block hook from returning the result from the action.

Returns

An object with the following properties:

  • execute(): A function that takes in the argument to run the action, the same as the argument for run().
  • result: the Result of running execute(). See the dedicated page for the type of this.
  • isPending: a boolean representing if the action is currently executing or transitioning.
  • isSuccess: a boolean representing if the action completed successfully.

On this page