@jay-js/system
Version:
A powerful and flexible TypeScript library for UI, state management, lazy loading, routing and managing draggable elements in modern web applications.
68 lines (67 loc) • 2.22 kB
TypeScript
import type { TMutationFetcher, TMutationOptions, TMutationStore } from "./types.js";
/**
* Creates a reactive mutation for write operations (POST/PUT/DELETE)
*
* Unlike queries, mutations don't cache results and are designed for write operations.
* They support optimistic updates with automatic rollback on error.
*
* @param fetcher Async function to perform mutation
* @param options Mutation configuration options
* @returns Mutation store with reactive states and control methods
*
* @example
* Basic usage:
* ```typescript
* const createUser = mutation(async (user: User, signal) => {
* const res = await fetch('/api/users', {
* method: 'POST',
* body: JSON.stringify(user),
* signal,
* });
* return res.json();
* });
*
* // Execute mutation
* await createUser.mutate({ name: 'John', email: 'john@example.com' });
* ```
*
* @example
* With optimistic updates:
* ```typescript
* const updateUser = mutation(
* async (user: User, signal) => {
* const res = await fetch(`/api/users/${user.id}`, {
* method: 'PUT',
* body: JSON.stringify(user),
* signal,
* });
* return res.json();
* },
* {
* onMutate: async (newUser) => {
* // Snapshot current state for rollback
* const previousUser = queryCache.get<User>(`user-${newUser.id}`);
*
* // Optimistically update cache
* if (previousUser) {
* queryCache.set(`user-${newUser.id}`, newUser, 300000);
* }
*
* return { previousUser };
* },
* onError: (err, variables, context) => {
* // Rollback on error
* if (context?.previousUser) {
* queryCache.set(`user-${variables.id}`, context.previousUser.data, 300000);
* }
* },
* onSuccess: () => {
* // Invalidate related queries
* queryCache.delete('users');
* },
* invalidateQueries: ['users', 'user-list'],
* }
* );
* ```
*/
export declare function mutation<TData = unknown, TError = Error, TVariables = void, TContext = unknown>(fetcher: TMutationFetcher<TData, TVariables>, options?: TMutationOptions<TData, TError, TVariables, TContext>): TMutationStore<TData, TError, TVariables, TContext>;