Hooks
useWrite
Trigger mutations with loading and error states
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"],
});Hook-Level Options
useWrite accepts a second argument for hook-level options. These options apply to all triggers from this hook:
const { trigger, meta } = useWrite((api) => api("posts").POST(), {
transform: (post) => ({
success: true,
postId: post.id,
createdAt: new Date(post.timestamp),
}),
});
await trigger({ body: { title: "New Post" } });
// meta.transformedData is available after trigger completesAvailable Hook Options
| Option | Type | Description |
|---|---|---|
transform | (data) => T | Transform response data at hook level |
| + plugin options | - | Hook-level options from installed plugins |
Returns
| Property | Type | Description |
|---|---|---|
trigger | (options) => Promise | Execute the mutation |
data | TData | undefined | Response data |
error | TError | undefined | Error if request failed |
loading | boolean | True while mutation is in progress |
abort | () => void | Abort current request |
input | object | undefined | The last trigger input |
meta | object | Plugin-provided metadata |
Trigger Options
| Option | Type | Description |
|---|---|---|
body | TBody | Request body |
query | TQuery | Query parameters |
params | Record<string, string | number> | Path parameters |
| + plugin options | - | Options from installed plugins |