Actions
fate does not provide hooks for mutations like traditional data fetching libraries do. Instead, mutations are exposed in two ways:
fate.actionsfor use withuseActionStateand React Actions.fate.mutationsfor traditional imperative mutation calls.
fate's Vite plugin makes your server mutations available on the client. The API works the same way with native HTTP, tRPC, GraphQL, and Void.
You can also define mutations for Client State. Components call them through the same fate.actions and fate.mutations APIs.
If you have a mutation named post.like, a LikeButton component using fate Actions and an async component library could look like this:
import { useActionState } from 'react';
import { useFateClient } from 'react-fate';
const LikeButton = ({ post }: { post: { id: string; likes: number } }) => {
const fate = useFateClient();
const [result, like] = useActionState(fate.actions.post.like, null);
return (
<Button action={() => like({ input: { id: post.id } })}>
{result?.error ? 'Oops!' : 'Like'}
</Button>
);
};If you are not using an async component library, you can use React's useTransition to start the action in a transition:
const LikeButton = ({ post }: { post: { id: string; likes: number } }) => {
const fate = useFateClient();
const [, startTransition] = useTransition();
const [result, like, isPending] = useActionState(fate.actions.post.like, null);
return (
<button
disabled={isPending}
onClick={() => {
startTransition(() =>
like({
input: { id: post.id },
}),
);
}}
>
{result?.error ? 'Oops!' : 'Like'}
</button>
);
};Optimistic Updates
Use an optimistic function to increment the cached like count while the mutation is pending.
like({
input: { id: post.id },
optimistic: (current) => (current.likes === undefined ? undefined : { likes: current.likes + 1 }),
persist: false,
});Views that select likes update immediately. Views that only select other fields, such as title, do not re-render. If the mutation fails, fate rolls back the optimistic update.
Fate reruns pending functions in submission order when confirmed data changes. Each function receives the cached record after earlier pending updates. Keep the function synchronous and pure. Cached fields can be missing. Return undefined to skip the update, or return one patch containing all the fields to update. The function can also read the mutation input as its second argument. Use a view or selection to request any result fields a conditional patch might update.
An object with fixed values, such as optimistic: { archived: true }, reapplies those values on every replay. Use a registered updater for offline replay. If live updates can include this mutation before its response arrives, use versioned snapshots to prevent double counting.
Inserting New Objects
Let's add a comment to a post. Pass the comments list as insert.into and give the optimistic comment a temporary ID:
const content = 'New Comment text';
addComment({
input: { content, postId: post.id },
insert: { into: post.comments, position: 'after' },
optimistic: {
author: { id: user.id, name: user.name },
content,
id: `optimistic:${Date.now().toString(36)}`,
post: { commentCount: post.commentCount + 1, id: post.id },
},
});The comment appears immediately. When the server responds, fate replaces the temporary ID with the real one. If the mutation fails, the comment disappears and the count is restored.
Use position: 'before' for a newest-first list. Without insert, fate updates existing records but does not add them to lists. See Controlling List Insertion Behavior for deferred lists and inserting into more than one list.
Selecting a View with Actions
Mutations may change data that is not directly specified in the mutation result. For example, adding a comment increases the post's comment count. For such cases, you can provide a view to an action that specifies which fields to fetch as part of the mutation:
addComment({
input: { content: 'New Comment text', postId: post.id },
view: view<Comment>()({
...CommentView,
post: { commentCount: true },
}),
});The server returns the selected fields, and views that display the post's comment count update automatically.
Use .with() before useActionState to include selected fields in state.result:
const [state, addComment] = useActionState(fate.actions.comment.add.with(CommentView), null);Pass a view or a raw selection. Chaining .with() adds fields to the existing selection, for example .with(CommentView).with({ post: { commentCount: true } }).
Mutations
Use fate.mutations to call a mutation outside a React Action, or when calls should run without waiting for earlier actions to finish:
const result = await fate.mutations.comment.add({
input: { content, postId: post.id },
});The options are the same as for Actions, including optimistic, insert, remove, invalidate, and view. The call returns a promise. Handle pending state and errors in the calling code.
If a mutation doesn't take any input, you can omit the arguments entirely. For example, our client counter increments with fate.mutations.counter.increment(). You can still pass options such as { view: CounterView }. Actions take an options object, so dispatch the same mutation with increment({}) inside a React Action or transition. Mutations that declare input fields still require input, even if every field is optional.
Mutation Server Implementation
Define mutations in your backend and return the fields requested by the client. See Server Integration for native HTTP and tRPC, GraphQL Integration for an existing GraphQL API, or Void Integration for a Void app.
Action & Mutation Error Handling
Expected errors, such as a validation failure or a 404, are returned in result.error. You can show a message next to the button or form:
const [result, deletePost] = useActionState(fate.actions.post.delete, null);
if (result?.error) {
return <p>Could not delete this post. Please try again.</p>;
}Network failures, server errors, and authentication or authorization errors are thrown. React Actions send them to the nearest error boundary:
<ErrorBoundary FallbackComponent={ErrorComponent}>
<Suspense fallback={<div>Loading…</div>}>
<PostPage postId={postId} />
</Suspense>
</ErrorBoundary>When calling fate.mutations directly, use try/catch to handle thrown errors. Both kinds of failure roll back optimistic updates. GraphQL error codes are described in Errors and Partial Results.
Deleting Records
Pass delete: true to remove an object immediately. fate also removes it from lists that contain it and restores it if the mutation fails:
const [result, deleteAction] = useActionState(fate.actions.post.delete, null);
deleteAction({
input: { id: post.id },
delete: true,
});Resetting Action State
To clear an action's result without sending another mutation, dispatch 'reset' inside a transition:
import { startTransition, useActionState } from 'react';
const [result, like] = useActionState(fate.actions.post.like, null);
const dismiss = () => startTransition(() => like('reset'));Controlling List Insertion Behavior
Choose which list should receive a new object with insert. For example, comments can be deferred and still used directly as an insertion target:
const PostCommentsView = view<Post>()({
comments: defer({
args: { first: 20 },
items: { node: CommentView },
}),
id: true,
});
// Inside a component that receives postRef:
const post = useView(PostCommentsView, postRef);
const addComment = () =>
fate.mutations.comment.add({
input: { content: 'New Comment text', postId: post.id },
insert: { into: post.comments, position: 'after' },
optimistic: {
content: 'New Comment text',
id: 'optimistic:new-comment',
},
view: CommentView,
});Passing post.comments does not fetch the comments. If they haven't loaded yet, fate keeps the insertion until they do. You can also pass a resolved array or connection from a request or view. Use the original value from the same client, rather than a copied or filtered array.
Use an array of insertion objects to update multiple lists, with an independent position for each:
await fate.mutations.comment.add({
input: { content, postId: post.id },
insert: [
{ into: post.comments, position: 'after' },
{ into: recentComments, position: 'before' },
],
view: CommentView,
});Only the named lists receive the new comment. Filters and sorting are still your app's choice: use before or after to match how each list is ordered. An object already in a list is updated without being duplicated or moved.
Insertions work with pagination, optimistic updates, and offline mutations. Appended comments stay after later pages as they load; prepended comments stay before earlier pages.
Migrating from automatic insertion
Earlier versions appended mutation results automatically. Add an insert option to calls that relied on that behavior. The strings 'before' and 'after' still enable automatic list matching, but prefer an explicit target. 'none' is now the default.
Removing Items from Lists
Let's say we want to move a post from the inbox to an archive. Pass the inbox list as remove.from and the post's view ref as remove.node. Use insert in the same call to add the post to the archive.
await fate.mutations.post.archive({
input: { id: postRef.id },
optimistic: { archived: true },
remove: { from: inbox, node: postRef },
insert: { into: archivedPosts, position: 'before' },
});The post disappears from the inbox immediately. If the mutation fails, fate rolls back both list changes. The post itself stays in the cache. Pass an array of removal objects to remove more than one item or update several lists.
await fate.mutations.post.archive({
input: { id: postRef.id },
remove: [
{ from: inbox, node: postRef },
{ from: starredPosts, node: postRef },
],
});Use the original array, connection, or deferred list returned by the same client. A deferred list still loads when a component reads it. If it loads while the mutation is pending, fate applies the removal to the loaded items. Removals also work with offline mutations.
If archiving the post changes which items the server would return on the first page, add the list to invalidate.
Invalidating Lists
Archiving a post might bring the next post into the first page of the inbox. Pass the inbox list to invalidate to fetch the updated page on the next request.
await fate.mutations.post.archive({
input: { id: postRef.id },
invalidate: [inbox],
});Use the original array or connection returned by the same client. When the mutation succeeds, fate marks the list stale and keeps its current items visible. The next cache-first request fetches the list again. Lists with other filters keep their cached results. To refresh the list immediately, use useRefetch.
Refreshing the first page replaces the previously loaded pages. You can load more pages from the refreshed list.
Invalidating Records
Let's add a comment to a post. If the mutation doesn't return the post's updated comment count, pass the post's view ref to invalidate.
await fate.mutations.comment.add({
input: { content, postId: postRef.id },
invalidate: [postRef],
});When the mutation succeeds, fate marks the post's cached fields stale. A cache-first request refreshes the fields it selects. If it selects only the title, the comment count stays stale until a request selects it. You can pass both view refs and lists to invalidate in the same call.