For AI agents: the complete documentation index is available at https://navios.tech/llms.txt, the full documentation bundle is available at https://navios.tech/llms-full.txt, and this page is available as Markdown at https://navios.tech/docs/builder/reference/react-query.md.

@navios/react-query API

Every public export of @navios/react-query, with signatures. This page is for looking things up; the React Query guides explain how the pieces are used. Requires @tanstack/react-query ^5.102.0.

declareClient

function declareClient(options: ClientOptions): ClientInstance
ClientOptions fieldTypeDescription
apiBuilderInstanceThe builder that inline declarations are declared on
defaultsKeyOptionskeyPrefix / keySuffix applied to every key made by this client

Client methods

Each method has two forms: pass an endpoint you already declared, or declare one inline. Inline, the endpoint options and the method's own options share one object.

client.query(endpoint, options?)
client.query({ ...endpointOptions, ...options })

client.infiniteQuery(endpoint, settings)
client.infiniteQuery({ ...endpointOptions, ...settings })

client.mutation(endpoint, settings?)
client.mutation({ ...endpointOptions, ...settings })
MethodOptions typeReturnsNotes
querySurfaceOptionsQueryObjectAny endpoint
infiniteQueryInfiniteQuerySettingsInfiniteQueryObjectThe endpoint must have a querySchema
mutationMutationSettingsMutationObjectAny endpoint, including multipart and blob

Unknown keys in an inline declaration are compile errors. Options given to a method override the client's defaults.

Shared options

SurfaceOptions is accepted by all three methods. KeyOptions is its first two fields.

OptionTypeDefaultDescription
keyPrefixreadonly unknown[][]Segments placed before [method, url] in every key
keySuffixreadonly unknown[][]Segments placed right after [method, url]
withResponsebooleanfalseDeliver DataWithResponse instead of the bare data

Query keys have the shape [...keyPrefix, method, url, ...keySuffix, 'with-response'?, 'infinite'?, inputs?], where inputs is { urlParams?, params?, data? }. Mutation keys are [...keyPrefix, method, url, ...keySuffix]. See Keys and invalidation.

Query object

QueryObject<Options, TData, TError>. args is the endpoint's call arguments; it is optional wherever the endpoint requires nothing. TError is the endpoint's typed EndpointError.

MemberSignatureDescription
query()(args, options?) => QueryOptionsResult<TData, TError>TanStack query options for useQuery, useSuspenseQuery, useQueries and queryClient.query
use(args | skipToken, options?) => UseQueryResult<TSelected, TError>useQuery. options is every TanStack option except queryKey and queryFn
useSuspense(args, options?) => UseSuspenseQueryResult<TSelected, TError>useSuspenseQuery, with the same rule for options
key(args?: PartialEndpointInputs<Options>) => TaggedKey<TData, TError>No args: every entry of the endpoint. Partial args: the matching entries. Full args: the exact key
fetch(queryClient, args) => Promise<TData>Fetches through the cache; fresh cached data is returned without a request. Rejects with TError
prefetch(queryClient, args) => Promise<void>Like fetch, but resolves with nothing and never rejects
ensure(queryClient, args) => Promise<TData>Cached data however old; fetches only when the cache is empty
getData(queryClient, args) => TData | undefinedReads the cached data
setData(queryClient, args, updater) => TData | undefinedWrites the cached data; updater is a value or (current) => next
invalidate(queryClient, args?, filters?) => Promise<void>Invalidates by the same scopes as key. filters is TanStack's, minus queryKey
endpointEndpointHandler<Options>The endpoint this query calls

See Queries.

Infinite query settings

InfiniteQuerySettings<Options, TPage> is SurfaceOptions plus:

SettingTypeDescription
getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) => PageParam<Options> | undefined | nullRequired. Query params of the next page, or nothing when there is none
getPreviousPageParam(firstPage, allPages, firstPageParam, allPageParams) => PageParam<Options> | undefined | nullThe same, backwards
initialPageParamPageParam<Options>Defaults to the call's params

PageParam<Options> is the input type of the endpoint's querySchema. Each page param is merged over the call's params.

Infinite query object

InfiniteQueryObject<Options, TPage, TError, TPageParam, TData> has the same members as a query object, with these differences:

  • The cached value, and so the type handled by fetch, ensure, getData and setData, is InfiniteData<TPage, TPageParam>.
  • use and useSuspense wrap useInfiniteQuery and useSuspenseInfiniteQuery. Their options also exclude getNextPageParam, getPreviousPageParam and initialPageParam, which come from the settings.
  • Calling the object returns InfiniteQueryOptionsResult.
  • Its keys carry an 'infinite' marker, so it never shares an entry with a plain query of the same endpoint.

See Infinite queries.

Mutation settings

MutationSettings is SurfaceOptions, plus every TanStack useMutation option except mutationFn and mutationKey (retry, scope, meta, gcTime, ...), plus:

SettingTypeDescription
invalidatesreadonly InvalidateTarget[]Invalidated after success. A query object means its whole endpoint; a function (data, variables) => key | undefined means that key
optimistic(update: OptimisticUpdater) => OptimisticUpdate | readonly OptimisticUpdate[]Cache updates applied before the request is sent
useContext() => TContextA hook run inside the mutation hook; its result is merged into every callback's context
onMutate(variables, context) => TOnMutateResultBefore the request
onSuccess(data, variables, context) => voidAfter success, alongside invalidates
onError(error, variables, context) => voidAfter failure; error is the endpoint's typed EndpointError
onSettled(data, error, variables, context) => voidAfter either

Callbacks may return a promise. context is MutationCallbackContext<TContext>: the result of useContext merged with TanStack's { client, meta, mutationKey }. In onSuccess, onError and onSettled it also has onMutateResult.

The update function given to optimistic takes a query object and an OptimisticUpdateSpec:

Spec fieldTypeDefaultDescription
args(variables) => args of the query—Selects the entry to update. Required when the query has required inputs
update(current | undefined, variables) => next | undefined—Returns the new cached value
rollbackOnErrorbooleantrueRestore the previous value when the mutation fails
invalidateOnSettledbooleantrueInvalidate the entry when the mutation settles

See Mutations and Optimistic updates.

Mutation object

MutationObject<Options, TOnMutateResult, TData, TError, TVariables> is itself the hook.

MemberSignatureDescription
mutation()() => UseMutationResult<TData, TError, TVariables, TOnMutateResult>useMutation. Takes no arguments; pass everything, URL params included, to mutate
mutationKeyreadonly unknown[]Key shared by every mutation of this endpoint
useIsMutating(match?: { urlParams?: Partial<UrlParams> }) => booleantrue while a mutation of this endpoint is in flight, optionally only for those URL params
endpointEndpointHandler<Options>The endpoint this mutation calls

TVariables is MutationVariables<Options>: the endpoint's call arguments, optional when the endpoint requires nothing.

withResponse and DataWithResponse

With withResponse: true, a query, infinite query page or mutation result is wrapped:

interface DataWithResponse<TData> {
  data: TData
  response: {
    status: number
    statusText: string
    headers: Record<string, string>
  }
}

Header names are lower-cased and headers is a plain record, so the value survives dehydration and persistence. Entries declared with withResponse live under their own key, marked 'with-response'. Failures still go to the error channel.

MaybeWithResponse<TData, WithResponse> is DataWithResponse<TData> when WithResponse is true, and TData otherwise.

setHttpClient and getHttpClient

function setHttpClient(queryClient: QueryClient, client: Client | null): void

function getHttpClient(queryClient: QueryClient): Client | undefined

setHttpClient binds an HTTP client to a QueryClient. Every query, infinite query and mutation run through that QueryClient then uses it instead of the builder's client. Pass null to remove the binding. See SSR and prefetching.

makeQuery, makeInfiniteQuery and makeMutation

The functions behind the client methods, for use without a client instance. They take an existing endpoint only, and no client defaults are applied.

function makeQuery(endpoint: EndpointHandler<Options>, options?: SurfaceOptions): QueryObject<Options>

function makeInfiniteQuery(
  endpoint: EndpointHandler<Options>,
  settings: InfiniteQuerySettings<Options>,
): InfiniteQueryObject<Options>

function makeMutation(
  endpoint: EndpointHandler<Options>,
  settings?: MutationSettings<Options>,
): MutationObject<Options>

Key utilities

The key-building functions the objects above use. Prefer query.key() and mutation.mutationKey; these exist for tooling that needs the same keys without a query object.

FunctionSignatureDescription
createKeyBuilder(config, options?, isInfinite?) => { base, key(args?), skipped() }Key builder for one endpoint config. skipped() is the key a hook uses under skipToken
createMutationKey(config, options?: KeyOptions) => readonly unknown[]The mutation key of an endpoint config
pickInputs(args: unknown) => Record<string, unknown> | undefinedReduces call arguments to urlParams, params and data; stringifies URL param values and drops empty parts
normalizeKeyValue(value: unknown) => unknownRewrites URLSearchParams, FormData, File, Blob, Map, Set and bigint into plain data that hashes by content
optimisticUpdate(query, spec: OptimisticUpdateSpec) => OptimisticUpdateThe function the optimistic setting hands to its callback

Types

TypeDescription
ClientInstanceWhat declareClient returns: { query, infiniteQuery, mutation }
ClientOptionsArgument of declareClient
KeyOptions{ keyPrefix?, keySuffix? }
SurfaceOptions<WithResponse>KeyOptions plus withResponse
EndpointArgs<Options>The full call arguments of an endpoint
EndpointInputs<Options>The part of the arguments that goes into the key: urlParams, params, data
PartialEndpointInputs<Options>Any subset of the inputs; the argument of key and invalidate
EndpointData<Options>The data an endpoint resolves to
EndpointFailure<Options>The typed EndpointError an endpoint fails with
ArgsWith<Options, Rest>[args, ...Rest], with args optional when nothing is required
RequiredKeys<T>Keys of T that must be provided
TaggedKey<TData, TError>A key tagged with the types stored under it
QueryHookOptions, SuspenseQueryHookOptionsThe options of use and useSuspense
QueryOptionsResult<TData, TError>What calling a query object returns
InvalidateFiltersTanStack's InvalidateQueryFilters without queryKey
InfiniteEndpointOptionsEndpoint options with a required querySchema
PageParam<Options>Input type of the endpoint's querySchema
InfiniteQueryHookOptions, SuspenseInfiniteQueryHookOptionsThe options of an infinite query's hooks
InfiniteQueryOptionsResultWhat calling an infinite query object returns
AnyQueryObjectAnything with a key function: a query or an infinite query
MutationVariables<Options>The variables passed to mutate
MutationCallbackContext<TContext>The context argument of the mutation callbacks
InvalidateTarget<TData, TVariables>One entry of invalidates
OptimisticUpdater<TVariables>The function the optimistic callback receives
OptimisticUpdateSpec<Q, TVariables>The description passed to it
OptimisticUpdate<TVariables>What it returns
QueryObject, InfiniteQueryObject, MutationObject, InfiniteQuerySettings, MutationSettings, DataWithResponse, MaybeWithResponseDescribed in their sections above