trigger.ts
Overview
The trigger.ts file is a TypeScript utility module that primarily contains a set of custom React hooks built on top of the useSWRMutation and useSWR hooks from the swr library. These hooks demonstrate usage patterns, type safety assertions, and advanced configurations when working with SWR mutations in React applications.
The core purpose of these hooks is to provide strongly-typed mutation triggers that allow invoking API mutations while ensuring type correctness of parameters and return values. Additionally, the file includes internal TypeScript utility types and functions used for compile-time type assertion tests.
This file is mainly used for:
Validating type safety for SWR mutation triggers.
Providing reusable wrapper hooks (
useTrigger,useTriggerWithParameter, etc.) that simplify mutation calls with typed arguments.Demonstrating advanced mutation options like error handling and optimistic updates.
Ensuring correct interaction with SWR's cache mutation and revalidation mechanisms.
Class / Function Documentation
The file contains only functions (React hooks) and TypeScript utility types/functions for type assertion. Below is a detailed explanation of each:
Type Definitions and Utilities
type ExpectType = <T>(value: T) => void
A generic utility type for type assertion in tests.
The function signature accepts a generic value
Tand returns void.Used to assert expected types during compile time.
const expectType: ExpectType = () => {}
A no-op implementation of the
ExpectTypefunction.Used purely for compile-time type assertions without runtime effect.
type Equal<A, B> = ...
A conditional TypeScript type that compares two types
Aand B.Returns
trueifAand B are exactly equal types, otherwisefalse.Used internally to assert type equality in the hooks.
useExtraParam()
export function useExtraParam(): void
Demonstrates the type inference behavior of
useSWRMutationwith different callback signatures.Calls
useSWRMutationtwice with/api/userkey and different mutation functions.Asserts that the
keyparameter passed to mutation function is a string.Asserts that the
optsargument in the mutation callback has the expected structure.No return value.
Usage Example:
useExtraParam();
// Used internally to verify parameter typings in mutation callbacks
useTrigger()
export function useTrigger(): void
Wraps
useSWRMutationwith/api/userkey.Defines a mutation function that converts a
numberargument into astring.Extracts and validates
trigger,reset,data, anderrorfrom the mutation result.Uses
expectTypeassertions to verify:triggeraccepts a number argument.triggerreturns aPromise<string>.resetis a void function.datais a string or undefined.erroris any type.
Checks that
mutateandisValidatingare omitted from the returned type.No return value.
Usage Example:
useTrigger();
// Used internally to verify typings of trigger and related mutation properties
useTriggerWithParameter()
export function useTriggerWithParameter(): void
Uses
useSWRMutationwith explicit generic parameters for data, error, key, and argument types.Mutation callback expects an argument of type
number.Asserts that
triggeraccepts anumberand returns aPromise<string>.Demonstrates calling
triggerwith an options object (throwOnError).No return value.
Usage Example:
useTriggerWithParameter();
// Internal test hook for typed trigger with explicit generic parameters and options
useOnErrorThrowFalse()
export function useOnErrorThrowFalse(): void
Similar to
useTriggerWithParameter, but passes an options object touseSWRMutationwiththrowOnError: false.Shows how the
throwOnErrorflag affects the return type oftrigger.Asserts that calling
triggerwithout options returnsPromise<string | undefined>.Calling with
throwOnError: truereturnsPromise<string>.No return value.
Usage Example:
useOnErrorThrowFalse();
// Demonstrates usage of throwOnError option in SWR mutation triggers
useTestSWRMutation()
export function useTestSWRMutation(): void
Combines
useSWRanduseSWRMutationhooks to test interactions.useSWRfetches a string array['foo'].useSWRMutationdefines a mutation that expects an argumentarg: 'foo'and converts it to uppercase.Contains a
testfunction that:Intentionally triggers TypeScript errors when
triggeris called without the required argument.Demonstrates usage of
triggerwith advanced mutation options likeoptimisticData,populateCache, andrevalidate.
Uses
expectTypeassertions to validate types of optimistic data and cache population.No return value.
Usage Example:
useTestSWRMutation();
// Used for testing strict argument typing and advanced mutation options
useTestSWRMutationWithOptionalArgs()
export function useTestSWRMutationWithOptionalArgs(): void
Defines a mutation with an optional argument
arg?: 'foo'.Calls
triggerwith argument'foo',undefined, and no argument.Asserts that the return type is
Promise<string | undefined>in all cases.No return value.
Usage Example:
useTestSWRMutationWithOptionalArgs();
// Tests SWR mutation triggers with optional arguments
useTestSWRMutationWithSWRMutate()
export function useTestSWRMutationWithSWRMutate(): void
Demonstrates interaction between
useSWRanduseSWRMutationon the same cache key.useSWRfetches an object{ foo: 'bar' }.useSWRMutationdefines a mutation that returns{ foo: 'foo' }.Inside a test function, calls
mutate(trigger(), { optimisticData: { foo: 'baz' } })to optimistically update the cache while triggering the mutation.No return value.
Usage Example:
useTestSWRMutationWithSWRMutate();
// Demonstrates optimistic cache updates with SWR's mutate and trigger
Important Implementation Details and Algorithms
The file does not implement new algorithms but focuses on type safety and usage patterns for the
useSWRMutationhook.Uses TypeScript's advanced type utilities (
Equal,ExpectType) for compile-time verification of type correctness.Leverages
Readonly<{ arg: T }>pattern for mutation options to enforce immutability.Demonstrates how the
throwOnErroroption influences the promise return type of trigger calls.Shows how to combine
useSWRdata fetching withuseSWRMutationmutation triggers on the same cache key.Uses optimistic updates and cache population patterns to ensure UI responsiveness during mutations.
Interaction with Other Parts of the System
useSWRanduseSWRMutationhooks fromswrlibrary: This file is tightly coupled with these SWR hooks, extending their usage with custom hooks that enforce stricter typing and usage patterns.API routes: All mutation hooks use the endpoint
/api/useror'key'/'/some/key'as cache keys, suggesting interaction with backend API endpoints.TypeScript type system: Heavily relies on types and generic parameters to ensure the system's type safety.
React components: These hooks are intended to be used within React function components to perform data mutations with SWR.
Visual Diagram
classDiagram
class useTrigger {
+trigger(arg: number): Promise<string>
+reset(): void
+data: string | undefined
+error: any
}
class useTriggerWithParameter {
+trigger(arg: number, options?): Promise<string | undefined>
}
class useOnErrorThrowFalse {
+trigger(arg: number, options?): Promise<string | undefined | string>
}
class useTestSWRMutation {
+trigger(arg: 'foo', options?): Promise<string>
+data: string[]
}
class useTestSWRMutationWithOptionalArgs {
+trigger(arg?: 'foo'): Promise<string | undefined>
}
class useTestSWRMutationWithSWRMutate {
+trigger(): Promise<{foo: string}>
+mutate(): void
}
class useExtraParam {
+void
}
useTrigger ..> useSWRMutation : uses
useTriggerWithParameter ..> useSWRMutation : uses
useOnErrorThrowFalse ..> useSWRMutation : uses
useTestSWRMutation ..> useSWRMutation : uses
useTestSWRMutationWithOptionalArgs ..> useSWRMutation : uses
useTestSWRMutationWithSWRMutate ..> useSWRMutation : uses
useTestSWRMutationWithSWRMutate ..> useSWR : uses
Summary
trigger.ts is a utility module that provides a set of strongly typed React hooks built with SWR's mutation hooks, focusing on type safety, argument validation, and usage patterns for mutation triggers. It serves as a test and demonstration suite for using useSWRMutation with varying argument types, mutation options, and SWR cache interactions, ensuring robust and predictable data mutation workflows in React applications.