Queries
This is the most basic feature of RTK Query. A query operation can be performed with any data fetching library of your choice, but the general recommendation is that you only use queries for requests that retrieve data. For anything that alters data on the server or will possibly invalidate the cache, you should use a Mutation.
By default, RTK Query ships with fetchBaseQuery
, which is a lightweight fetch
wrapper that automatically handles request headers and response parsing in a manner similar to common libraries like axios
.
Depending on your environment, you may need to polyfill
fetch
withnode-fetch
orcross-fetch
if you choose to usefetchBaseQuery
orfetch
on its own.
Performing queries with React Hooks
If you're using React Hooks, RTK Query does a few additional things for you. The primary benefit is that you get a render-optimized hook that allows you to have 'background fetching' as well as derived booleans for convenience.
Hooks are automatically generated based on the name of the endpoint
in the service definition. An endpoint field with getPost: builder.query()
will generate a hook named useGetPostQuery
.
Hook types
There are 3 query-related hooks:
useQuery
- Composes
useQuerySubscription
anduseQueryState
and is the primary hook.
- Composes
useQuerySubscription
- Returns a
refetch
function and accepts all hook options
- Returns a
useQueryState
- Returns the query state and accepts
skip
andselectFromResult
- Returns the query state and accepts
Query Hook Options
- skip - Defaults to
false
- pollingInterval - Defaults to
0
(off) - selectFromResult - Optional, allows you to return a subset of a query
- refetchOnMountOrArgChange - Defaults to
false
- refetchOnFocus - Defaults to
false
- refetchOnReconnect - Defaults to
false
All
refetch
-related options will override the defaults you may have set in createApi
Query Hook Return Types
Here is an example of a PostDetail
component:
The way that this component is setup would have some nice traits:
It only shows 'Loading...' on the initial load
- Initial load is defined as a query that is pending and does not have data in the cache
When the request is re-triggered by the polling interval, it will add '...refetching' to the post name
If a user closed this
PostDetail
, but then re-opened it within the allowed time, they would immediately be served a cached result and polling would resume with the previous behavior.
Selecting data from a query result
Sometimes you may have a parent component that is subscribed to a query, and then in a child component you want to pick an item from that query. In most cases you don't want to perform an additional request for a getItemById
-type query when you know that you already have the result. selectFromResult
allows you to get a specific segment from a query result in a performant manner. When using this feature, the component will not rerender unless the underlying data of the selected item has changed. If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
Query Cache Keys
When you perform a query, RTK Query automatically serializes the request parameters and creates an internal queryCacheKey
for the request. Any future request that produces the same queryCacheKey
will be de-duped against the original, and will share updates if a refetch
is trigged on the query from any subscribed component.
Avoiding unnecessary requests
By default, if you add a component that makes the same query as an existing one, no request will be performed.
In some cases, you may want to skip this behavior and force a refetch - in that case, you can call refetch
that is returned by the hook.
If you're not using React Hooks, you can access
refetch
like this:const { status, data, error, refetch } = dispatch(pokemonApi.endpoints.getPokemon.initiate('bulbasaur'));
Observing caching behavior
What you'll see below is this:
The first
Pokemon
component mounts and immediately fetches 'bulbasaur'A second later, another
Pokemon
component is rendered with 'bulbasaur'- Notice that this one doesn't ever show 'Loading...' and no new network request happens? It's using the cache here.
A moment after that, a
Pokemon
component for 'pikachu' is added, and a new request happens.When you click 'Refetch' of a particular pokemon type, it'll update all of them with one request.
Try it out
Click the 'Add bulbasaur' button. You'll observe the same behavior described above until you click the 'Refetch' button on one of the components.