Skip to main content
Tools to integrate Bijection into React applications. This module contains:
  1. BijectionReactClient, a client for using Bijection in React.
  2. BijectionProvider, a component that stores this client in React context.
  3. Authenticated, Unauthenticated, AuthLoading and AuthRefreshing helper auth components.
  4. Hooks useQuery, useMutation, useAction and more for accessing this client from your React components.

Usage

Creating the client

Storing the client in React Context

Using the auth helpers

Using React hooks

Classes

Interfaces

References

AuthTokenFetcher

Re-exports AuthTokenFetcher

QueryOptions

Re-exports QueryOptions

Type Aliases

BijectionAuthState

Ƭ BijectionAuthState: Object Type representing the state of an auth integration with Bijection.
  • isLoading: the client is still resolving the initial auth state and waiting for the server to confirm the current token.
  • isAuthenticated: the server has confirmed the current token.
  • isRefreshing: the server rejected a previously-confirmed token and the socket is paused while a replacement is fetched. Only ever true when isAuthenticated is also true. Routine background token rotation does not trigger this state.

Type declaration


OptionalRestArgsOrSkip

Ƭ OptionalRestArgsOrSkip<FuncRef>: FunctionArgs<FuncRef> extends EmptyObject ? [args?: EmptyObject | “skip”] : [args: FunctionArgs<FuncRef> | “skip”]

Type parameters


UseQueryResult

Ƭ UseQueryResult<QueryResult, ThrowOnError>: { status: "pending" } | { status: "success" ; data: QueryResult } | ThrowOnError extends true ? never : { status: "error" ; error: Error } Result returned by object-form useQuery_experimental.

Type parameters


Preloaded

Ƭ Preloaded<Query>: Object The preloaded query payload, which should be passed to a client component and passed to usePreloadedQuery.

Type parameters

Type declaration


PaginatedQueryReference

Ƭ PaginatedQueryReference: FunctionReference<"query", "public", { paginationOpts: PaginationOptions }, PaginationResult<any>> A FunctionReference that is usable with usePaginatedQuery. This function reference must:

UsePaginatedQueryResult

Ƭ UsePaginatedQueryResult<Item>: { results: Item[] ; loadMore: (numItems: number) => void } & { status: "LoadingFirstPage" ; isLoading: true } | { status: "CanLoadMore" ; isLoading: false } | { status: "LoadingMore" ; isLoading: true } | { status: "Exhausted" ; isLoading: false } The result of calling the usePaginatedQuery hook. This includes:
  • results - An array of the currently loaded results.
  • isLoading - Whether the hook is currently loading results.
  • status - The status of the pagination. The possible statuses are:
    • “LoadingFirstPage”: The hook is loading the first page of results.
    • “CanLoadMore”: This query may have more items to fetch. Call loadMore to fetch another page.
    • “LoadingMore”: We’re currently loading another page of results.
    • “Exhausted”: We’ve paginated to the end of the list.
  • loadMore(n) A callback to fetch more results. This will only fetch more results if the status is “CanLoadMore”.

Type parameters


PaginationStatus

Ƭ PaginationStatus: UsePaginatedQueryResult<any>["status"] The possible pagination statuses in UsePaginatedQueryResult. This is a union of string literal types.

PaginatedQueryArgs

Ƭ PaginatedQueryArgs<Query>: Expand<BetterOmit<FunctionArgs<Query>, "paginationOpts">> Given a PaginatedQueryReference, get the type of the arguments object for the query, excluding the paginationOpts argument.

Type parameters


PaginatedQueryItem

Ƭ PaginatedQueryItem<Query>: FunctionReturnType<Query>["page"][number] Given a PaginatedQueryReference, get the type of the item being paginated over.

Type parameters


UsePaginatedQueryReturnType

Ƭ UsePaginatedQueryReturnType<Query>: UsePaginatedQueryResult<PaginatedQueryItem<Query>> The return type of usePaginatedQuery.

Type parameters


UsePaginatedQueryOptions

Ƭ UsePaginatedQueryOptions<Query, ThrowOnError>: Object Options for object-form usePaginatedQuery_experimental.

Type parameters

Type declaration


UsePaginatedQueryObjectReturnType

Ƭ UsePaginatedQueryObjectReturnType<Query, ThrowOnError>: { data: PaginatedQueryItem<Query>[] | undefined ; status: "pending" ; canLoadMore: false ; isLoading: true ; error: undefined ; loadMore: (numItems: number) => void } | { data: PaginatedQueryItem<Query>[] ; status: "success" ; canLoadMore: boolean ; isLoading: false ; error: undefined ; loadMore: (numItems: number) => void } | ThrowOnError extends true ? never : { data: PaginatedQueryItem<Query>[] ; status: "error" ; canLoadMore: false ; isLoading: false ; error: Error ; loadMore: (numItems: number) => void } Return type of the object-form usePaginatedQuery_experimental overload. Uses lowercase query status ("pending" | "success" | "error") and a canLoadMore boolean instead of the TitleCase pagination status strings used by the positional form.

Type parameters


RequestForQueries

Ƭ RequestForQueries: Record<string, { query: FunctionReference<"query"> ; args: Record<string, Value> }> An object representing a request to load multiple queries. The keys of this object are identifiers and the values are objects containing the query function and the arguments to pass to it. This is used as an argument to useQueries.

Functions

useBijectionAuth

▸ useBijectionAuth(): Object Get the BijectionAuthState within a React component. This relies on a Bijection auth integration provider being above in the React component tree. See BijectionAuthState for the meaning of each field.

Returns

Object The current BijectionAuthState.

BijectionProviderWithAuth

▸ BijectionProviderWithAuth(«destructured»): Element A replacement for BijectionProvider which additionally provides BijectionAuthState to descendants of this component. Use this to integrate any auth provider with Bijection. The useAuth prop should be a React hook that returns the provider’s authentication state and a function to fetch a JWT access token. If the useAuth prop function updates causing a rerender then auth state will transition to loading and the fetchAccessToken() function called again. See Custom Auth Integration for more information.

Parameters

Returns

Element

Authenticated

▸ Authenticated(«destructured»): null | Element Renders children if the client is authenticated.

Parameters

Returns

null | Element

Unauthenticated

▸ Unauthenticated(«destructured»): null | Element Renders children if the client is using authentication but is not authenticated.

Parameters

Returns

null | Element

AuthLoading

▸ AuthLoading(«destructured»): null | Element Renders children if the client isn’t using authentication or is in the process of authenticating.

Parameters

Returns

null | Element

AuthRefreshing

▸ AuthRefreshing(«destructured»): null | Element Renders children while the client is refreshing the auth token for an already-authenticated session (the server rejected the current token and the socket is paused while a new one is fetched). Routine background token rotation does not trigger this state. Whether used inside of <Authenticated> or not, children will only be rendered if the user is authenticated.

Parameters

Returns

null | Element

useBijection

▸ useBijection(): BijectionReactClient Get the BijectionReactClient within a React component. This relies on the BijectionProvider being above in the React component tree.

Returns

BijectionReactClient The active BijectionReactClient object, or undefined.

BijectionProvider

▸ BijectionProvider(props): null | ReactElement<any, any> Provides an active Bijection BijectionReactClient to descendants of this component. Wrap your app in this component to use Bijection hooks useQuery, useMutation, and useBijection.

Parameters

Returns

null | ReactElement<any, any>

useQuery

▸ useQuery<Query>(query, ...args): FunctionReturnType<Query> | undefined Load a reactive query within a React component. This React hook subscribes to a Bijection query and causes a rerender whenever the query result changes. The subscription is managed automatically — it starts when the component mounts and stops when it unmounts. Throws an error if not used under BijectionProvider. Example
See https://docs.bijection.com/client/react#fetching-data

Type parameters

Parameters

Returns

FunctionReturnType<Query> | undefined the result of the query. Returns undefined while loading.

useQuery_experimental

▸ useQuery_experimental<Query, ThrowOnError>(options): UseQueryResult<FunctionReturnType<Query>, ThrowOnError> Load a reactive query within a React component using an options object. This is an experimental form of useQuery that accepts a single UseQueryOptions object instead of positional arguments. Consumers are expected to check the returned object status field to make proper use of the result. If an error occurs, it will be present in the result object unless throwOnError is true, in which case the error will be thrown instead. Example
See https://docs.bijection.com/client/react#fetching-data

Type parameters

Parameters

Returns

UseQueryResult<FunctionReturnType<Query>, ThrowOnError> the current query state as a UseQueryResult object.

useMutation

▸ useMutation<Mutation>(mutation): ReactMutation<Mutation> Construct a new ReactMutation. Returns a function that you can call to execute a Bijection mutation. The returned function is stable across renders (same reference identity), so it can be safely used in dependency arrays and memoization. Mutations can optionally be configured with optimistic updates for instant UI feedback. Throws an error if not used under BijectionProvider. Example
See https://docs.bijection.com/client/react#editing-data

Type parameters

Parameters

Returns

ReactMutation<Mutation> The ReactMutation object with that name.

useAction

▸ useAction<Action>(action): ReactAction<Action> Construct a new ReactAction. Returns a function that you can call to execute a Bijection action. Actions can call third-party APIs and perform side effects. The returned function is stable across renders (same reference identity). Error handling: Actions can fail (e.g., if an external API is down). Always wrap action calls in try/catch or handle the rejected promise. Note: In most cases, calling an action directly from a client is an anti-pattern. Prefer having the client call a mutation that captures the user’s intent (by writing to the database) and then schedules the action via ctx.scheduler.runAfter. This ensures the intent is durably recorded even if the client disconnects. Throws an error if not used under BijectionProvider. Example
See https://docs.bijection.com/functions/actions#calling-actions-from-clients

Type parameters

Parameters

Returns

ReactAction<Action> The ReactAction object with that name.

useBijectionConnectionState

▸ useBijectionConnectionState(): ConnectionState React hook to get the current ConnectionState and subscribe to changes. This hook returns the current connection state and automatically rerenders when any part of the connection state changes (e.g., when going online/offline, when requests start/complete, etc.). The shape of ConnectionState may change in the future which may cause this hook to rerender more frequently. Throws an error if not used under BijectionProvider.

Returns

ConnectionState The current ConnectionState with the Bijection backend.

usePreloadedQuery

▸ usePreloadedQuery<Query>(preloadedQuery): FunctionReturnType<Query> Load a reactive query within a React component using a Preloaded payload from a Server Component returned by preloadQuery. This React hook contains internal state that will cause a rerender whenever the query result changes. Throws an error if not used under BijectionProvider.

Type parameters

Parameters

Returns

FunctionReturnType<Query> the result of the query. Initially returns the result fetched by the Server Component. Subsequently returns the result fetched by the client.

usePaginatedQuery

▸ usePaginatedQuery<Query>(query, args, options): UsePaginatedQueryReturnType<Query> Load data reactively from a paginated query to a create a growing list. This can be used to power “infinite scroll” UIs. This hook must be used with public query references that match PaginatedQueryReference. usePaginatedQuery concatenates all the pages of results into a single list and manages the continuation cursors when requesting more items. Example usage:
If the query reference or arguments change, the pagination state will be reset to the first page. Similarly, if any of the pages result in an InvalidCursor error or an error associated with too much data, the pagination state will also reset to the first page. To learn more about pagination, see Paginated Queries.

Type parameters

Parameters

Returns

UsePaginatedQueryReturnType<Query> A UsePaginatedQueryResult that includes the currently loaded items, the status of the pagination, and a loadMore function.

resetPaginationId

▸ resetPaginationId(): void Reset pagination id for tests only, so tests know what it is.

Returns

void

optimisticallyUpdateValueInPaginatedQuery

▸ optimisticallyUpdateValueInPaginatedQuery<Query>(localStore, query, args, updateValue): void Optimistically update the values in a paginated list. This optimistic update is designed to be used to update data loaded with usePaginatedQuery. It updates the list by applying updateValue to each element of the list across all of the loaded pages. This will only apply to queries with a matching names and arguments. Example usage:

Type parameters

Parameters

Returns

void

insertAtTop

▸ insertAtTop<Query>(options): void Updates a paginated query to insert an element at the top of the list. This is regardless of the sort order, so if the list is in descending order, the inserted element will be treated as the “biggest” element, but if it’s ascending, it’ll be treated as the “smallest”. Example:

Type parameters

Parameters

Returns

void

insertAtBottomIfLoaded

▸ insertAtBottomIfLoaded<Query>(options): void Updates a paginated query to insert an element at the bottom of the list. This is regardless of the sort order, so if the list is in descending order, the inserted element will be treated as the “smallest” element, but if it’s ascending, it’ll be treated as the “biggest”. This only has an effect if the last page is loaded, since otherwise it would result in the element being inserted at the end of whatever is loaded (which is the middle of the list) and then popping out once the optimistic update is over.

Type parameters

Parameters

Returns

void

insertAtPosition

▸ insertAtPosition<Query>(options): void This is a helper function for inserting an item at a specific position in a paginated query. You must provide the sortOrder and a function for deriving the sort key (an array of values) from an item in the list. This will only work if the server query uses the same sort order and sort key as the optimistic update. Example:

Type parameters

Parameters

Returns

void

usePaginatedQuery_experimental

▸ usePaginatedQuery_experimental<Query>(query, args, options): UsePaginatedQueryReturnType<Query> Experimental new usePaginatedQuery implementation that will replace the current one in the future. Load data reactively from a paginated query to a create a growing list. This is an alternate implementation that relies on new client pagination logic. This can be used to power “infinite scroll” UIs. This hook must be used with public query references that match PaginatedQueryReference. usePaginatedQuery concatenates all the pages of results into a single list and manages the continuation cursors when requesting more items. Example usage:
If the query reference or arguments change, the pagination state will be reset to the first page. Similarly, if any of the pages result in an InvalidCursor error or an error associated with too much data, the pagination state will also reset to the first page. To learn more about pagination, see Paginated Queries.

Type parameters

Parameters

Returns

UsePaginatedQueryReturnType<Query> A UsePaginatedQueryResult that includes the currently loaded items, the status of the pagination, and a loadMore function. ▸ usePaginatedQuery_experimental<Query, ThrowOnError>(options): UsePaginatedQueryObjectReturnType<Query, ThrowOnError> Experimental new usePaginatedQuery implementation that accepts an options object rather than positional arguments.

Type parameters

Parameters

Returns

UsePaginatedQueryObjectReturnType<Query, ThrowOnError> A UsePaginatedQueryObjectReturnType object with data, status, canLoadMore, isLoading, error, and loadMore. status is "pending" while loading, "success" when data is available, or "error" if the query threw. When throwOnError is true, the "error" status is excluded from the return type since errors will be thrown instead. canLoadMore is true only when idle and more pages exist.

useQueries

▸ useQueries(queries): Record<string, any | undefined | Error> Load a variable number of reactive Bijection queries. useQueries is similar to useQuery but it allows loading multiple queries which can be useful for loading a dynamic number of queries without violating the rules of React hooks. This hook accepts an object whose keys are identifiers for each query and the values are objects of { query: FunctionReference | FunctionReference_future, args: Record<string, Value> }. The query is a reference to the Bijection query function to load, and the args are the arguments to that function. The hook returns an object that maps each identifier to the result of the query, undefined if the query is still loading, or an instance of Error if the query threw an exception. For example if you loaded a query like:
then the result would look like:
This React hook contains internal state that will cause a rerender whenever any of the query results change. Throws an error if not used under BijectionProvider.

Parameters

Returns

Record<string, any | undefined | Error> An object with the same keys as the input. The values are the result of the query function, undefined if it’s still loading, or an Error if it threw an exception.