Module: react
Tools to integrate Convex into React applications.
This module contains:
- ConvexReactClient, a client for using Convex in React.
- ConvexProvider, a component that stores this client in React context.
- Authenticated, Unauthenticated and AuthLoading helper auth components.
- Hooks useQuery, useMutation, useAction and more for accessing this client from your React components.
Usage
Creating the client
import { ConvexReactClient } from "convex/react";
// typically loaded from an environment variable
const address = "https://small-mouse-123.convex.cloud"
const convex = new ConvexReactClient(address);
Storing the client in React Context
import { ConvexProvider } from "convex/react";
<ConvexProvider client={convex}>
<App />
</ConvexProvider>
Using the auth helpers
import { Authenticated, Unauthenticated, AuthLoading } from "convex/react";
<Authenticated>
Logged in
</Authenticated>
<Unauthenticated>
Logged out
</Unauthenticated>
<AuthLoading>
Still loading
</AuthLoading>
Using React hooks
import { useQuery, useMutation } from "convex/react";
import { api } from "../convex/_generated/api";
function App() {
const counter = useQuery(api.getCounter.default);
const increment = useMutation(api.incrementCounter.default);
// Your component here!
}
Classes
Interfaces
Type Aliases
AuthTokenFetcher
Ƭ AuthTokenFetcher: (args
: { forceRefreshToken
: boolean
}) => Promise
<string
| null
| undefined
>
Type declaration
▸ (args
): Promise
<string
| null
| undefined
>
An async function returning the JWT-encoded OpenID Connect Identity Token if available.
forceRefreshToken
is true
if the server rejected a previously
returned token, and the client should try to fetch a new one.
See setAuth.
Parameters
Name | Type |
---|---|
args | Object |
args.forceRefreshToken | boolean |
Returns
Promise
<string
| null
| undefined
>
Defined in
browser/sync/authentication_manager.ts:20
ConvexAuthState
Ƭ ConvexAuthState: Object
Type representing the state of an auth integration with Convex.
Type declaration
Name | Type |
---|---|
isLoading | boolean |
isAuthenticated | boolean |
Defined in
OptionalRestArgsOrSkip
Ƭ OptionalRestArgsOrSkip<FuncRef
>: FuncRef
["_args"
] extends EmptyObject
? [args?: EmptyObject | "skip"] : [args: FuncRef["_args"] | "skip"]
Type parameters
Name | Type |
---|---|
FuncRef | extends FunctionReference <any > |
Defined in
Preloaded
Ƭ Preloaded<Query
>: Object
The preloaded query payload, which should be passed to a client component and passed to usePreloadedQuery.
Type parameters
Name | Type |
---|---|
Query | extends FunctionReference <"query" > |
Type declaration
Name | Type |
---|---|
__type | Query |
_name | string |
_argsJSON | string |
_valueJSON | string |
Defined in
PaginatedQueryReference
Ƭ PaginatedQueryReference: FunctionReference
<"query"
, "public"
, { paginationOpts
: PaginationOptions
}, PaginationResult
<any
>>
A FunctionReference that is usable with usePaginatedQuery.
This function reference must:
- Refer to a public query
- Have an argument named "paginationOpts" of type PaginationOptions
- Have a return type of PaginationResult.
Defined in
react/use_paginated_query.ts:29
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
Name |
---|
Item |
Defined in
react/use_paginated_query.ts:430
PaginationStatus
Ƭ PaginationStatus: UsePaginatedQueryResult
<any
>["status"
]
The possible pagination statuses in UsePaginatedQueryResult.
This is a union of string literal types.
Defined in
react/use_paginated_query.ts:458
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
Name | Type |
---|---|
Query | extends PaginatedQueryReference |
Defined in
react/use_paginated_query.ts:466
PaginatedQueryItem
Ƭ PaginatedQueryItem<Query
>: FunctionReturnType
<Query
>["page"
][number
]
Given a PaginatedQueryReference, get the type of the item being paginated over.
Type parameters
Name | Type |
---|---|
Query | extends PaginatedQueryReference |
Defined in
react/use_paginated_query.ts:475
UsePaginatedQueryReturnType
Ƭ UsePaginatedQueryReturnType<Query
>: UsePaginatedQueryResult
<PaginatedQueryItem
<Query
>>
The return type of usePaginatedQuery.
Type parameters
Name | Type |
---|---|
Query | extends PaginatedQueryReference |
Defined in
react/use_paginated_query.ts:483
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.
Defined in
Functions
useConvexAuth
▸ useConvexAuth(): Object
Get the ConvexAuthState within a React component.
This relies on a Convex auth integration provider being above in the React component tree.
Returns
Object
The current ConvexAuthState.
Name | Type |
---|---|
isLoading | boolean |
isAuthenticated | boolean |
Defined in
ConvexProviderWithAuth
▸ ConvexProviderWithAuth(«destructured»
): Element
A replacement for ConvexProvider which additionally provides ConvexAuthState to descendants of this component.
Use this to integrate any auth provider with Convex. The useAuth
prop
should be a React hook that returns the provider's authentication state
and a function to fetch a JWT access token.
See Custom Auth Integration for more information.
Parameters
Name | Type |
---|---|
«destructured» | Object |
› children? | ReactNode |
› client | IConvexReactClient |
› useAuth | () => { isLoading : boolean ; isAuthenticated : boolean ; fetchAccessToken : (args : { forceRefreshToken : boolean }) => Promise <null | string > } |
Returns
Element
Defined in
Authenticated
▸ Authenticated(«destructured»
): null
| Element
Renders children if the client is authenticated.
Parameters
Name | Type |
---|---|
«destructured» | Object |
› children | ReactNode |
Returns
null
| Element
Defined in
Unauthenticated
▸ Unauthenticated(«destructured»
): null
| Element
Renders children if the client is using authentication but is not authenticated.
Parameters
Name | Type |
---|---|
«destructured» | Object |
› children | ReactNode |
Returns
null
| Element
Defined in
AuthLoading
▸ AuthLoading(«destructured»
): null
| Element
Renders children if the client isn't using authentication or is in the process of authenticating.
Parameters
Name | Type |
---|---|
«destructured» | Object |
› children | ReactNode |
Returns
null
| Element
Defined in
useConvex
▸ useConvex(): ConvexReactClient
Get the ConvexReactClient within a React component.
This relies on the ConvexProvider being above in the React component tree.
Returns
The active ConvexReactClient object, or undefined
.
Defined in
ConvexProvider
▸ ConvexProvider(props
, deprecatedLegacyContext?
): null
| ReactElement
<any
, any
>
Provides an active Convex ConvexReactClient to descendants of this component.
Wrap your app in this component to use Convex hooks useQuery
,
useMutation
, and useConvex
.
Parameters
Name | Type | Description |
---|---|---|
props | Object | an object with a client property that refers to a ConvexReactClient. |
props.client | ConvexReactClient | - |
props.children? | ReactNode | - |
deprecatedLegacyContext? | any | Deprecated See React Docs |
Returns
null
| ReactElement
<any
, any
>
Defined in
../../common/temp/node_modules/.pnpm/@types+react@18.3.5/node_modules/@types/react/ts5.0/index.d.ts:1115
useQuery
▸ useQuery<Query
>(query
, ...args
): Query
["_returnType"
] | undefined
Load a reactive query within a React component.
This React hook contains internal state that will cause a rerender whenever the query result changes.
Throws an error if not used under ConvexProvider.
Type parameters
Name | Type |
---|---|
Query | extends FunctionReference <"query" > |
Parameters
Name | Type | Description |
---|---|---|
query | Query | a FunctionReference for the public query to run like api.dir1.dir2.filename.func . |
...args | OptionalRestArgsOrSkip <Query > | The arguments to the query function or the string "skip" if the query should not be loaded. |
Returns
Query
["_returnType"
] | undefined
the result of the query. If the query is loading returns undefined
.
Defined in
useMutation
▸ useMutation<Mutation
>(mutation
): ReactMutation
<Mutation
>
Construct a new ReactMutation.
Mutation objects can be called like functions to request execution of the corresponding Convex function, or further configured with optimistic updates.
The value returned by this hook is stable across renders, so it can be used by React dependency arrays and memoization logic relying on object identity without causing rerenders.
Throws an error if not used under ConvexProvider.
Type parameters
Name | Type |
---|---|
Mutation | extends FunctionReference <"mutation" > |
Parameters
Name | Type | Description |
---|---|---|
mutation | Mutation | A FunctionReference for the public mutation to run like api.dir1.dir2.filename.func . |
Returns
ReactMutation
<Mutation
>
The ReactMutation object with that name.
Defined in
useAction
▸ useAction<Action
>(action
): ReactAction
<Action
>
Construct a new ReactAction.
Action objects can be called like functions to request execution of the corresponding Convex function.
The value returned by this hook is stable across renders, so it can be used by React dependency arrays and memoization logic relying on object identity without causing rerenders.
Throws an error if not used under ConvexProvider.
Type parameters
Name | Type |
---|---|
Action | extends FunctionReference <"action" > |
Parameters
Name | Type | Description |
---|---|---|
action | Action | A FunctionReference for the public action to run like api.dir1.dir2.filename.func . |
Returns
ReactAction
<Action
>
The ReactAction object with that name.
Defined in
usePreloadedQuery
▸ usePreloadedQuery<Query
>(preloadedQuery
): Query
["_returnType"
]
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 ConvexProvider.
Type parameters
Name | Type |
---|---|
Query | extends FunctionReference <"query" > |
Parameters
Name | Type | Description |
---|---|---|
preloadedQuery | Preloaded <Query > | The Preloaded query payload from a Server Component. |
Returns
Query
["_returnType"
]
the result of the query. Initially returns the result fetched by the Server Component. Subsequently returns the result fetched by the client.
Defined in
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:
const { results, status, isLoading, loadMore } = usePaginatedQuery(
api.messages.list,
{ channel: "#general" },
{ initialNumItems: 5 }
);
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
Name | Type |
---|---|
Query | extends PaginatedQueryReference |
Parameters
Name | Type | Description |
---|---|---|
query | Query | A FunctionReference to the public query function to run. |
args | "skip" | Expand <BetterOmit <FunctionArgs <Query >, "paginationOpts" >> | The arguments object for the query function, excluding the paginationOpts property. That property is injected by this hook. |
options | Object | An object specifying the initialNumItems to be loaded in the first page. |
options.initialNumItems | number | - |
Returns
UsePaginatedQueryReturnType
<Query
>
A UsePaginatedQueryResult that includes the currently loaded
items, the status of the pagination, and a loadMore
function.
Defined in
react/use_paginated_query.ts:160
resetPaginationId
▸ resetPaginationId(): void
Reset pagination id for tests only, so tests know what it is.
Returns
void
Defined in
react/use_paginated_query.ts:409
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:
const myMutation = useMutation(api.myModule.myMutation)
.withOptimisticUpdate((localStore, mutationArg) => {
// Optimistically update the document with ID `mutationArg`
// to have an additional property.
optimisticallyUpdateValueInPaginatedQuery(
localStore,
api.myModule.paginatedQuery
{},
currentValue => {
if (mutationArg === currentValue._id) {
return {
...currentValue,
"newProperty": "newValue",
};
}
return currentValue;
}
);
});
Type parameters
Name | Type |
---|---|
Query | extends PaginatedQueryReference |
Parameters
Name | Type | Description |
---|---|---|
localStore | OptimisticLocalStore | An OptimisticLocalStore to update. |
query | Query | A FunctionReference for the paginated query to update. |
args | Expand <BetterOmit <FunctionArgs <Query >, "paginationOpts" >> | The arguments object to the query function, excluding the paginationOpts property. |
updateValue | (currentValue : PaginatedQueryItem <Query >) => PaginatedQueryItem <Query > | A function to produce the new values. |
Returns
void
Defined in
react/use_paginated_query.ts:529
useQueries
▸ useQueries(queries
): Record
<string
, any
| undefined
| Error
>
Load a variable number of reactive Convex 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, args: Record<string, Value> }
. The
query
is a FunctionReference for the Convex 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:
const results = useQueries({
messagesInGeneral: {
query: "listMessages",
args: { channel: "#general" }
}
});
then the result would look like:
{
messagesInGeneral: [{
channel: "#general",
body: "hello"
_id: ...,
_creationTime: ...
}]
}
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 ConvexProvider.
Parameters
Name | Type | Description |
---|---|---|
queries | RequestForQueries | An object mapping identifiers to objects of {query: string, args: Record<string, Value> } describing which query functions to fetch. |
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.