Spoosh
Hooks

useWrite

Trigger mutations with loading and error states

Trigger mutations with loading and error states. The callback selects the API method (no parentheses).

Basic Usage

function CreateUser() {
  const { trigger, loading, error } = useWrite(
    (api) => api("users").POST
  );

  const handleSubmit = async (formData: CreateUserBody) => {
    const result = await trigger({ body: formData });

    if (result.data) {
      console.log("Created:", result.data);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button disabled={loading}>
        {loading ? "Creating..." : "Create User"}
      </button>
    </form>
  );
}

With Invalidation

const { trigger } = useWrite((api) => api("posts").POST);

await trigger({
  body: { title: "New Post", content: "..." },
  invalidate: ["posts"],
});

Returns

PropertyTypeDescription
trigger(options) => PromiseExecute the mutation
dataTData | undefinedResponse data
errorTError | undefinedError if request failed
loadingbooleanTrue while mutation is in progress
abort() => voidAbort current request
inputobject | undefinedThe last trigger input
metaobjectPlugin-provided metadata

Trigger Options

OptionTypeDescription
bodyTBodyRequest body
queryTQueryQuery parameters
paramsRecord<string, string | number>Path parameters
+ plugin options-Options from installed plugins

On this page