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 for calling into this client within 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>
Generating typed hooks
This module is typically used alongside generated hooks.
To generate the hooks, run npx convex dev
in your Convex project. This
will create a convex/_generated/react.js
file with the following React
hooks, typed for your queries and mutations:
If you aren't using code generation, you can use these untyped hooks instead:
Using the hooks
import { useQuery, useMutation } from "../convex/_generated/react";
function App() {
const counter = useQuery("getCounter");
const increment = useMutation("incrementCounter");
// 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:16
ConvexAuthState
Ƭ ConvexAuthState: Object
Type representing the state of an auth integration with Convex.
Type declaration
Name | Type |
---|---|
isLoading | boolean |
isAuthenticated | boolean |
Defined in
UseQueryForAPI
Ƭ UseQueryForAPI<API
>: <Name>(name
: Name
, ...argsAndOptions
: ArgsAndOptions
<NamedQuery
<API
, Name
>, UseQueryOptions
>) => ReturnType
<NamedQuery
<API
, Name
>> | undefined
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ <Name
>(name
, ...argsAndOptions
): ReturnType
<NamedQuery
<API
, Name
>> | undefined
Internal type helper used by Convex code generation.
Used to give useQueryGeneric a type specific to your API.
Type parameters
Name | Type |
---|---|
Name | extends PublicQueryNames <API > |
Parameters
Name | Type |
---|---|
name | Name |
...argsAndOptions | ArgsAndOptions <NamedQuery <API , Name >, UseQueryOptions > |
Returns
ReturnType
<NamedQuery
<API
, Name
>> | undefined
Defined in
UseMutationForAPI
Ƭ UseMutationForAPI<API
>: <Name>(name
: Name
) => ReactMutation
<API
, Name
>
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ <Name
>(name
): ReactMutation
<API
, Name
>
Internal type helper used by Convex code generation.
Used to give useMutationGeneric a type specific to your API.
Type parameters
Name | Type |
---|---|
Name | extends PublicMutationNames <API > |
Parameters
Name | Type |
---|---|
name | Name |
Returns
ReactMutation
<API
, Name
>
Defined in
UseActionForAPI
Ƭ UseActionForAPI<API
>: <Name>(name
: Name
) => ReactAction
<API
, Name
>
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ <Name
>(name
): ReactAction
<API
, Name
>
Internal type helper used by Convex code generation.
Used to give useMutationGeneric a type specific to your API.
Type parameters
Name | Type |
---|---|
Name | extends PublicActionNames <API > |
Parameters
Name | Type |
---|---|
name | Name |
Returns
ReactAction
<API
, Name
>
Defined in
UseConvexForAPI
Ƭ UseConvexForAPI<API
>: () => ConvexReactClient
<API
>
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ (): ConvexReactClient
<API
>
Internal type helper used by Convex code generation.
Used to give useConvexGeneric a type specific to your API.
Returns
ConvexReactClient
<API
>
Defined in
UsePaginatedQueryResult
Ƭ UsePaginatedQueryResult<T
>: { results
: T
[] ; 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 usePaginatedQueryGeneric 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 |
---|
T |
Defined in
react/use_paginated_query.ts:296
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:324
PaginatedQueryFunction
Ƭ PaginatedQueryFunction<Args
, ReturnType
>: (args
: { paginationOpts
: PaginationOptions
} & Args
) => PaginationResult
<ReturnType
>
Type parameters
Name | Type |
---|---|
Args | extends object |
ReturnType | ReturnType |
Type declaration
▸ (args
): PaginationResult
<ReturnType
>
A query function that is usable with usePaginatedQueryGeneric.
The function's argument must be an object with a
paginationOpts
property of type PaginationOptions.
The function must return a PaginationResult.
Parameters
Name | Type |
---|---|
args | { paginationOpts : PaginationOptions } & Args |
Returns
PaginationResult
<ReturnType
>
Defined in
react/use_paginated_query.ts:336
PaginatedQueryNames
Ƭ PaginatedQueryNames<API
>: { [QueryName in PublicQueryNames<API>]: IsPaginatedQueryFunction<NamedQuery<API, QueryName>> extends true ? QueryName : never }[PublicQueryNames
<API
>]
The names of the paginated query functions in a Convex API.
These are normal query functions that match PaginatedQueryFunction.
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Defined in
react/use_paginated_query.ts:363
PaginatedQueryArgs
Ƭ PaginatedQueryArgs<Query
>: Expand
<BetterOmit
<Parameters
<Query
>[0
], "paginationOpts"
>>
The type of the arguments to a PaginatedQueryFunction.
This type includes the entire arguments object except the paginationOpts
property.
Type parameters
Name | Type |
---|---|
Query | extends PaginatedQueryFunction <any , any > |
Defined in
react/use_paginated_query.ts:379
PaginatedQueryReturnType
Ƭ PaginatedQueryReturnType<Query
>: Query
extends PaginatedQueryFunction
<any
, infer ReturnType> ? ReturnType
: never
The return type of a PaginatedQueryFunction.
This is the type of the inner document or object within the PaginationResult that a paginated query function returns.
Type parameters
Name | Type |
---|---|
Query | extends PaginatedQueryFunction <any , any > |
Defined in
react/use_paginated_query.ts:390
UsePaginatedQueryForAPI
Ƭ UsePaginatedQueryForAPI<API
>: <Name>(name
: Name
, args
: PaginatedQueryArgs
<NamedQuery
<API
, Name
>>, options
: { initialNumItems
: number
}) => UsePaginatedQueryResult
<PaginatedQueryReturnType
<NamedQuery
<API
, Name
>>>
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ <Name
>(name
, args
, options
): UsePaginatedQueryResult
<PaginatedQueryReturnType
<NamedQuery
<API
, Name
>>>
Internal type helper used by Convex code generation.
Used to give usePaginatedQueryGeneric a type specific to your API.
Type parameters
Name | Type |
---|---|
Name | extends PaginatedQueryNames <API > |
Parameters
Name | Type |
---|---|
name | Name |
args | PaginatedQueryArgs <NamedQuery <API , Name >> |
options | Object |
options.initialNumItems | number |
Returns
UsePaginatedQueryResult
<PaginatedQueryReturnType
<NamedQuery
<API
, Name
>>>
Defined in
react/use_paginated_query.ts:403
RequestForQueries
Ƭ RequestForQueries: Record
<string
, { name
: string
; 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 name of the query function and the arguments to pass to it.
This is used as an argument to useQueriesGeneric.
Defined in
UseQueriesForAPI
Ƭ UseQueriesForAPI<API
>: <QueryNameMap>(queries
: { [Identifier in keyof QueryNameMap]: Object }) => { [Identifier in keyof QueryNameMap]: ReturnType<NamedQuery<API, QueryNameMap[Identifier]>> | undefined | Error }
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Type declaration
▸ <QueryNameMap
>(queries
): { [Identifier in keyof QueryNameMap]: ReturnType<NamedQuery<API, QueryNameMap[Identifier]>> | undefined | Error }
Internal type helper used by Convex code generation.
Used to give useQueriesGeneric a type specific to your API.
Type parameters
Name | Type |
---|---|
QueryNameMap | extends Record <string , PublicQueryNames <API >> |
Parameters
Name | Type |
---|---|
queries | { [Identifier in keyof QueryNameMap]: Object } |
Returns
{ [Identifier in keyof QueryNameMap]: ReturnType<NamedQuery<API, QueryNameMap[Identifier]>> | undefined | Error }
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
useConvexGeneric
▸ useConvexGeneric<API
>(): ConvexReactClient
<API
>
Get the ConvexReactClient within a React component.
This relies on the ConvexProvider being above in the React component tree.
If you're using code generation, use the useConvex
function in
convex/_generated/react.js
which is typed for your API.
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Returns
ConvexReactClient
<API
>
The active ConvexReactClient object, or undefined
.
Defined in
ConvexProvider
▸ ConvexProvider(props
, context?
): 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 | PropsWithChildren <{ client : ConvexReactClient <any > ; children? : ReactNode }> | an object with a client property that refers to a ConvexReactClient. |
context? | any | - |
Returns
null
| ReactElement
<any
, any
>
Defined in
../../common/temp/node_modules/.pnpm/@types+react@17.0.58/node_modules/@types/react/index.d.ts:542
useQueryGeneric
▸ useQueryGeneric(name
, args?
, _options?
): unknown
| 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.
If you're using code generation, use the useQuery
function in
convex/_generated/react.js
which is typed for your API.
Parameters
Name | Type | Description |
---|---|---|
name | string | The name of the query function. |
args? | Record <string , Value > | The arguments to the query function. |
_options? | UseQueryOptions | - |
Returns
unknown
| undefined
the result of the query. If the query is loading returns undefined
.
Defined in
useMutationGeneric
▸ useMutationGeneric<API
, Name
>(name
): ReactMutation
<API
, Name
>
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.
If you're using code generation, use the useMutation
function in
convex/_generated/react.js
which is typed for your API.
Throws an error if not used under ConvexProvider.
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Name | extends string |
Parameters
Name | Type | Description |
---|---|---|
name | Name | The name of the mutation. |
Returns
ReactMutation
<API
, Name
>
The ReactMutation object with that name.
Defined in
useActionGeneric
▸ useActionGeneric<API
, Name
>(name
): ReactAction
<API
, Name
>
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.
If you're using code generation, use the useAction
function in
convex/_generated/react.js
which is typed for your API.
Throws an error if not used under ConvexProvider.
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Name | extends string |
Parameters
Name | Type | Description |
---|---|---|
name | Name | The name of the action. |
Returns
ReactAction
<API
, Name
>
The ReactAction object with that name.
Defined in
usePaginatedQueryGeneric
▸ usePaginatedQueryGeneric(name
, args
, options
): UsePaginatedQueryResult
<any
>
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 Convex query functions that match PaginatedQueryFunction. This means they must:
- Have a single arguments object with a
paginationOpts
property of type PaginationOptions. - Return a PaginationResult.
usePaginatedQueryGeneric
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 } = usePaginatedQueryGeneric(
"listMessages",
{ channel: "#general" },
{ initialNumItems: 5 }
);
If the query name
or args
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.
If you're using code generation, use the usePaginatedQuery
function in
convex/_generated/react.js
which is typed for your API.
Parameters
Name | Type | Description |
---|---|---|
name | string | The name of the query function. |
args | Record <string , Value > | 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
A UsePaginatedQueryResult that includes the currently loaded
items, the status of the pagination, and a loadMore
function.
Defined in
react/use_paginated_query.ts:62
optimisticallyUpdateValueInPaginatedQuery
▸ optimisticallyUpdateValueInPaginatedQuery<API
, Name
>(localStore
, name
, args
, updateValue
): void
Optimistically update the values in a paginated list.
This optimistic update is designed to be used to update data loaded with
usePaginatedQueryGeneric. 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("myMutationName")
.withOptimisticUpdate((localStore, mutationArg) => {
// Optimistically update the document with ID `mutationArg`
// to have an additional property.
optimisticallyUpdateValueInPaginatedQuery(
localStore,
"paginatedQueryName",
{},
currentValue => {
if (mutationArg.equals(currentValue._id)) {
return {
...currentValue,
"newProperty": "newValue",
};
}
return currentValue;
}
);
});
Type parameters
Name | Type |
---|---|
API | extends GenericAPI |
Name | extends string |
Parameters
Name | Type | Description |
---|---|---|
localStore | OptimisticLocalStore <API > | - |
name | Name | The name of the paginated query function. |
args | Expand <BetterOmit <Parameters <NamedQuery <API , Name >>[0 ], "paginationOpts" >> | The arguments object to the query function, excluding the paginationOpts property. |
updateValue | (currentValue : PaginatedQueryReturnType <NamedQuery <API , Name >>) => PaginatedQueryReturnType <NamedQuery <API , Name >> | A function to produce the new values. |
Returns
void
Defined in
react/use_paginated_query.ts:453
useQueriesGeneric
▸ useQueriesGeneric(queries
): Record
<string
, any
| undefined
| Error
>
Load a variable number of reactive Convex queries.
useQueriesGeneric
is similar to useQueryGeneric 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 { name: string, args: Record<string, Value> }
. The
name
is the name of 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 = useQueriesGeneric({
messagesInGeneral: {
name: "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.
If you're using code generation, use the useQueries
function in
convex/_generated/react.js
which is typed for your API.
Parameters
Name | Type | Description |
---|---|---|
queries | RequestForQueries | An object mapping identifiers to objects of {name: 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.