A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://redux-toolkit.js.org/rtk-query/api/created-api/hooks below:

API Slices: React Hooks | Redux Toolkit

API Slices: React Hooks Hooks Overview

The core RTK Query createApi method is UI-agnostic, in the same way that the Redux core library and Redux Toolkit are UI-agnostic. They are all plain JS logic that can be used anywhere. So, if you import createApi from '@reduxjs/toolkit/query', it does not have any specific UI integrations included.

However, RTK Query also provides the ability to auto-generate React hooks for each of your endpoints. Since this specifically depends on React itself, RTK Query provides an additional entry point that exposes a customized version of createApi that includes that functionality:

import { createApi } from '@reduxjs/toolkit/query/react'

If you have used the React-specific version of createApi, the generated api slice structure will also contain a set of React hooks. The primary endpoint hooks are available as api.endpoints[endpointName].useQuery, api.endpoints[endpointName].useMutation, and api.endpoints[endpointName].useInfiniteQuery, matching how you defined that endpoint.

Generated Hook Names

The same hooks are also added to the api object itself, and given auto-generated names based on the endpoint name and query/mutation type.

For example, if you had endpoints for getPosts and updatePost, these options would be available:

Generated React Hook names


const { data } = api.endpoints.getPosts.useQuery()
const [updatePost, { data }] = api.endpoints.updatePost.useMutation()


const { data } = api.useGetPostsQuery()
const [updatePost, { data }] = api.useUpdatePostMutation()

The general format is use(Endpointname)(Query|Mutation|InfiniteQuery) - use is prefixed, the first letter of your endpoint name is capitalized, then Query or Mutation or InfiniteQuery is appended depending on the type.

Available Hooks

RTK Query provides additional hooks for more advanced use-cases, although not all are generated directly on the api object as well.

Most of the hooks are generated on a per-endpoint basis.

The full list of hooks generated in the React-specific version of createApi is:

For the example above, the full set of generated hooks for the api would be like so:

Generated React Hooks


api.endpoints.getPosts.useQuery(arg, options)
api.endpoints.getPosts.useQueryState(arg, options)
api.endpoints.getPosts.useQuerySubscription(arg, options)
api.endpoints.getPosts.useLazyQuery(options)
api.endpoints.getPosts.useLazyQuerySubscription(options)


api.endpoints.getManyPosts.useInfiniteQuery(arg, options)
api.endpoints.getManyPosts.useInfiniteQueryState(arg, options)
api.endpoints.getManyPosts.useInfiniteQuerySubscription(arg, options)


api.endpoints.updatePost.useMutation(options)



api.useGetPostsQuery(arg, options)

api.useLazyGetPostsQuery(arg, options)

api.useUpdatePostMutation(arg, options)

api.useGetManyPostsInfiniteQuery(arg, options)

api.usePrefetch(endpointName, options)
Feature Comparison

The provided hooks have a degree of feature overlap in order to provide options optimized for a given situation. The table below provides a comparison of the core features for each hook.

Feature useQuery useMutation useQueryState useQuerySubscription useLazyQuery useLazyQuerySubscription usePrefetch Automatically triggers query requests ✔️ ✔️

Allows manually triggering query requests

✔️ ✔️ ✔️ ✔️ ✔️

Allows manually triggering mutation requests

✔️

Subscribes a component to keep cached data in the store

✔️ ✔️ ✔️ ✔️ ✔️

Returns request status and cached data from the store

✔️ ✔️ ✔️ ✔️

Re-renders as request status and data become available

✔️ ✔️ ✔️ ✔️

Accepts polling/re-fetching options to trigger automatic re-fetches

✔️ ✔️ ✔️ ✔️ Primary Hooks

These hooks are the main methods you will use to interact with RTK Query in your React components. They encapsulate all of logic and options needed for most data fetching and update use cases.

useQuery

Accessing a useQuery hook

const useQueryResult = api.endpoints.getPosts.useQuery(arg, options)

const useQueryResult = api.useGetPostsQuery(arg, options)

A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.

The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.

This hook combines the functionality of both useQueryState and useQuerySubscription together, and is intended to be used in the majority of situations.

Features useQuery Signature
type UseQuery = (
arg: any | SkipToken,
options?: UseQueryOptions,
) => UseQueryResult

type UseQueryOptions = {
pollingInterval?: number
skipPollingIfUnfocused?: boolean
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseQueryResult<T> = {



originalArgs?: unknown

data?: T

currentData?: T

error?: unknown

requestId?: string

endpointName?: string

startedTimeStamp?: number

fulfilledTimeStamp?: number




isUninitialized: boolean

isLoading: boolean

isFetching: boolean

isSuccess: boolean

isError: boolean


refetch: () => QueryActionCreatorResult
}
skipToken

Can be passed into useQuery, useQueryState or useQuerySubscription instead of the query argument to get the same effect as if setting skip: true in the query options.

Useful for scenarios where a query should be skipped when arg is undefined and TypeScript complains about it because arg is not allowed to be passed in as undefined, such as

will error if the query argument is not allowed to be undefined

useSomeQuery(arg, { skip: !!arg })

using skipToken instead

useSomeQuery(arg ?? skipToken)

If passed directly into a query or mutation selector, that selector will always return an uninitialized state.

See also Skipping queries with TypeScript using skipToken

useMutation

Accessing a useMutation hook

const useMutationResult = api.endpoints.updatePost.useMutation(options)

const useMutationResult = api.useUpdatePostMutation(options)

A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.

Features useMutation Signature
type UseMutation = (
options?: UseMutationStateOptions,
) => [UseMutationTrigger, UseMutationResult | SelectedUseMutationResult]

type UseMutationStateOptions = {

selectFromResult?: (result: UseMutationStateDefaultResult) => any

fixedCacheKey?: string
}

type UseMutationTrigger<T> = (arg: any) => Promise<
{ data: T } | { error: BaseQueryError | SerializedError }
> & {
requestId: string
abort: () => void
unwrap: () => Promise<T>
reset: () => void
}

type UseMutationResult<T> = {



originalArgs?: unknown

data?: T

error?: unknown

endpointName?: string

fulfilledTimeStamp?: number




isUninitialized: boolean

isLoading: boolean

isSuccess: boolean

isError: boolean

startedTimeStamp?: number


reset: () => void
}

tip

The generated UseMutation hook will cause a component to re-render by default after the trigger callback is fired, as it affects the properties of the result. If you want to call the trigger but don't care about subscribing to the result with the hook, you can use the selectFromResult option to limit the properties that the hook cares about.

Returning a completely empty object will mean that any individual mutation call will cause only one re-render at most, e.g.

selectFromResult: () => ({})
useInfiniteQuery

Accessing a useQuery hook

const useQueryResult = api.endpoints.getManyPosts.useInfiniteQuery(arg, options)

const useQueryResult = api.useGetManyPostsInfiniteQuery(arg, options)

A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.

The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.

The data field will be a {pages: Data[], pageParams: PageParam[]} structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.

This hook combines the functionality of both useInfiniteQueryState and useInfiniteQuerySubscription together, and is intended to be used in the majority of situations.

As with normal query hooks, skipToken is a valid argument that will skip the query from executing.

By default, the initial request will use the initialPageParam value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass initialPageParam as part of the hook options to override that initial request value.

Use the returned fetchNextPage and fetchPreviousPage methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided getNext/PreviousPageParam callbacks defined in the endpoint.

Features useInfiniteQuery Signature
type UseInfiniteQuery = (
arg: any | SkipToken,
options?: UseQueryOptions,
) => UseInfiniteQueryResult

type InfiniteData<Data, PageParam> = {
pages: Array<Data>
pageParams: Array<PageParam>
}

type UseInfiniteQueryOptions = {
pollingInterval?: number
skipPollingIfUnfocused?: boolean
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
selectFromResult?: (result: UseQueryStateDefaultResult) => any
initialPageParam?: PageParam
}

type UseInfiniteQueryResult<Data, PageParam> = {



originalArgs?: unknown

data?: InfiniteData<Data, PageParam>

currentData?: InfiniteData<Data, PageParam>

error?: unknown

requestId?: string

endpointName?: string

startedTimeStamp?: number

fulfilledTimeStamp?: number




isUninitialized: boolean

isLoading: boolean

isFetching: boolean

isSuccess: boolean

isError: boolean




hasNextPage: boolean

hasPreviousPage: boolean

isFetchingNextPage: boolean

isFetchingPreviousPage: boolean

isFetchNextPageError: boolean

isFetchPreviousPageError: boolean


refetch: () => InfiniteQueryActionCreatorResult


fetchNextPage: () => InfiniteQueryActionCreatorResult

fetchPreviousPage: () => InfiniteQueryActionCreatorResult
}
Secondary Hooks

These hooks are useful for specific additional use cases in your application, but will probably not be used that frequently.

useLazyQuery

Accessing a useLazyQuery hook

const [trigger, result, lastPromiseInfo] =
api.endpoints.getPosts.useLazyQuery(options)

const [trigger, result, lastPromiseInfo] = api.useLazyGetPostsQuery(options)

A React hook similar to useQuery, but with manual control over when the data fetching occurs.

This hook includes the functionality of useLazyQuerySubscription.

Features Note

When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set preferCacheValue(the second argument to the function) as true if you want it to immediately return a cached value if one exists.

useLazyQuery Signature
type UseLazyQuery = (
options?: UseLazyQueryOptions
) => [UseLazyQueryTrigger, UseLazyQueryStateResult, UseLazyQueryLastPromiseInfo]

type UseLazyQueryOptions = {
pollingInterval?: number
skipPollingIfUnfocused?: boolean
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseLazyQueryTrigger<T> = (arg: any, preferCacheValue?: boolean) => Promise<
QueryResultSelectorResult
> & {

arg: unknown

requestId: string

subscriptionOptions: SubscriptionOptions


abort: () => void

unwrap: () => Promise<T>

unsubscribe: () => void

refetch: () => void

updateSubscriptionOptions: (options: SubscriptionOptions) () => void
}

type UseLazyQueryStateResult<T> = {



originalArgs?: unknown

data?: T

currentData?: T

error?: unknown

requestId?: string

endpointName?: string

startedTimeStamp?: number

fulfilledTimeStamp?: number




isUninitialized: boolean

isLoading: boolean

isFetching: boolean

isSuccess: boolean

isError: boolean
}

type UseLazyQueryLastPromiseInfo = {
lastArg: any
}
usePrefetch

Accessing a usePrefetch hook

const prefetchCallback = api.usePrefetch(endpointName, options)

A React hook which can be used to initiate fetching data ahead of time.

Features Signature
type UsePrefetch = (
endpointName: string,
options?: UsePrefetchOptions,
) => PrefetchCallback

type UsePrefetchOptions =
| {


ifOlderThan?: false | number
}
| {


force?: boolean
}

type PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => void
Implementation Hooks

This hooks exist as implementation details of the primary hooks. They may be useful in rare cases, but you should generally use the primary hooks in your apps.

useQueryState

Accessing a useQuery hook

const useQueryStateResult = api.endpoints.getPosts.useQueryState(arg, options)

A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.

Note that this hook does not trigger fetching new data. For that use-case, see useQuery or useQuerySubscription.

Features useQueryState Signature
type UseQueryState = (
arg: any | SkipToken,
options?: UseQueryStateOptions,
) => UseQueryStateResult | SelectedQueryStateResult

type UseQueryStateOptions = {
skip?: boolean
selectFromResult?: (result: UseQueryStateDefaultResult) => any
}

type UseQueryStateResult<T> = {



originalArgs?: unknown

data?: T

currentData?: T

error?: unknown

requestId?: string

endpointName?: string

startedTimeStamp?: number

fulfilledTimeStamp?: number




isUninitialized: boolean

isLoading: boolean

isFetching: boolean

isSuccess: boolean

isError: boolean
}
useQuerySubscription

Accessing a useQuerySubscription hook

const { refetch } = api.endpoints.getPosts.useQuerySubscription(arg, options)

A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.

The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.

Note that this hook does not return a request status or cached data. For that use-case, see useQuery or useQueryState.

Features useQuerySubscription Signature
type UseQuerySubscription = (
arg: any | SkipToken,
options?: UseQuerySubscriptionOptions,
) => UseQuerySubscriptionResult

type UseQuerySubscriptionOptions = {
skip?: boolean
refetchOnMountOrArgChange?: boolean | number
pollingInterval?: number
skipPollingIfUnfocused?: boolean
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
}

type UseQuerySubscriptionResult = {
refetch: () => void
}
useInfiniteQueryState

Accessing a useInfiniteQueryState hook

const useInfiniteQueryStateResult =
api.endpoints.getManyPosts.useInfiniteQueryState(arg, options)

A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.

Note that this hook does not trigger fetching new data. For that use-case, see useInfiniteQuery or useInfiniteQuerySubscription.

Features useInfiniteQuerySubscription

Accessing a useInfiniteQuerySubscription hook

const useInfiniteQuerySubscriptionResult =
api.endpoints.getManyPosts.useInfiniteQuerySubscription(arg, options)

A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.

The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.

Note that this hook does not return a request status or cached data. For that use-case, see useInfiniteQuery or useInfiniteQueryState.

Features useLazyQuerySubscription

Accessing a useLazyQuerySubscription hook

const [trigger, lastArg] =
api.endpoints.getPosts.useLazyQuerySubscription(options)

A React hook similar to useQuerySubscription, but with manual control over when the data fetching occurs.

Note that this hook does not return a request status or cached data. For that use-case, see useLazyQuery.

Features useLazyQuerySubscription Signature
type UseLazyQuerySubscription = (
options?: UseLazyQuerySubscriptionOptions,
) => [UseLazyQuerySubscriptionTrigger, LastArg]

type UseLazyQuerySubscriptionOptions = {
pollingInterval?: number
skipPollingIfUnfocused?: boolean
refetchOnReconnect?: boolean
refetchOnFocus?: boolean
}

type UseLazyQuerySubscriptionTrigger = (
arg: any,
preferCacheValue?: boolean,
) => void

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4