MENU
Query
The most important function in Redux Toolkit Query, createApi() returns a slice with members that you can mount to your redux store, as well as hooks that you can use to fetch data from the defined endpoints.
Notice how the hook useGetPostQuery() is automatically generated from the endpoint 'getPost'.
If you don't want to automatically trigger the query request, you should use useLazyQuery() instead of useQuery().
isLoading refers to a query being in flight for the first time for the given hook. No data will be available at this time.
isFetching refers to a query being in flight for the given endpoint + query param combination, but not necessarily for the first time. Data may be available from an earlier request done by this hook, maybe with the previous query param.
You can split the operation of useQuery() into two steps: useQueryState() and useQuerySubscription(), which are accessible via api.endpoints.
The hook useLazyQuerySubscription() also exists.
An options object may be passed as the second argument to the hooks useQuery[State|Subscription](), or as the only argument to useLazyQuery[Subscription]().
Eg. This creates a real-time effect:
useGetPostQuery(123,{pollingInterval:30000});
option key | useQuery | useQueryState | useQuerySubscription | useLazyQuery | useLazyQuerySubscription |
pollingInterval: number (0) The interval in milliseconds to poll for (refetch) the data. |
√ | √ | √ | √ | |
refetchOnReconnect: boolean (false) Allows forcing the query to refetch when regaining a network connection. |
√ | √ | √ | √ | |
refetchOnFocus: boolean (false) Allows forcing the query to refetch when the browser window regains focus. |
√ | √ | √ | √ | |
skip: boolean (false) Allows a query to 'skip' running for that render. |
√ | √ | √ | ||
refetchOnMountOrArgChange: boolean | number (false) Allows forcing the query to always refetch on mount (when true is provided). Allows forcing the query to refetch if enough time (in seconds) has passed since the last query for the same cache (when a number is provided). |
√ | √ | |||
selectFromResult: (result: UseQueryStateDefaultResult) => any Allows altering the returned value of the hook to obtain a subset of the result, render-optimized for the returned subset. |
√ | √ | √ |
If the selected item is one element in a larger collection, it will disregard changes to the other elements in the same collection when deciding whether to re-render.
// An array declared here will maintain a stable reference rather than be re-created again
const emptyArray: Post[] = []
function PostsList() {
// This call will result in an initial render returning an empty array for `posts`,
// and a second render when the data is received.
// It will trigger additional rerenders only if the `posts` data changes
const { posts } = api.useGetPostsQuery(undefined, {
selectFromResult: ({ data }) => ({
posts: data ?? emptyArray,
}),
})
return (
<ul>
{posts.map((post) => (
<PostById key={post.id} id={post.id} />
))}
</ul>
)
}