new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Redux Toolkit · RTK Query · all subjects

createapi/refetching

25 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

refetchOnMountOrArgChange parameter

refetchOnMountOrArgChange can be a boolean or number (in seconds) and can be set globally in createApi. It can also be overridden by passing refetchOnMountOrArgChange to individual hook calls or by passing forceRefetch: true when dispatching the initiate action.

refetchOnFocus parameter

refetchOnFocus can be set globally in createApi and can be overridden by passing refetchOnFocus to individual hook calls or when dispatching the initiate action. If you specify track: false when manually dispatching queries, RTK Query will not be able to automatically refetch for you.

refetchOnReconnect parameter

refetchOnReconnect can be set globally in createApi and can be overridden by passing refetchOnReconnect to individual hook calls or when dispatching the initiate action. If you specify track: false when manually dispatching queries, RTK Query will not be able to automatically refetch for you.

usePrefetch hook generation

The React-specific version of createApi automatically generates a usePrefetch hook attached to the API object, which can be used to initiate fetching data ahead of time.

setupListeners purpose and basic usage

setupListeners is a utility that enables refetchOnFocus and refetchOnReconnect behaviors in RTK Query. It requires the dispatch method from your store. Calling setupListeners(store.dispatch) configures listeners with recommended defaults.

setupListeners function signature

setupListeners accepts two parameters: dispatch (required, of type ThunkDispatch<any, any, any>) and customHandler (optional callback). The customHandler callback receives dispatch and an object containing onFocus, onFocusLost, onOnline, and onOffline action creators, and must return a function that unsubscribes listeners.

setupListeners default event listeners

The default handler sets up four window event listeners: visibilitychange (dispatches onFocus when visible, onFocusLost when hidden), focus (dispatches onFocus), online (dispatches onOnline), and offline (dispatches onOffline). These listeners are only initialized once, controlled by an initialized flag.

setupListeners return value

setupListeners returns either the result of the customHandler callback or the default handler. Both must return an unsubscribe function that removes all event listeners and resets the initialized flag to false.

Accessing refetch actions via api.internalActions

The onFocus, onFocusLost, onOffline, and onOnline actions are made available through api.internalActions and can be manually dispatched. For example, dispatch(api.internalActions.onFocus()) manually triggers a focus event.

setupListeners example with custom handler

You can pass a customHandler callback to setupListeners for granular control over event listener setup. The callback receives dispatch and an actions object with onFocus, onFocusLost, onOnline, and onOffline, and must return an unsubscribe function.

RTK Query supports polling

RTK Query supports polling for automatic periodic refetching of query data.

Polling middleware matches queryThunk actions

The polling middleware uses queryThunk matching with the following logic: if queryThunk.pending.match(action) or (queryThunk.rejected.match(action) and action.meta.condition is true), updatePollingInterval is called. If queryThunk.fulfilled.match(action) or (queryThunk.rejected.match(action) and action.meta.condition is false), startNextPoll is called.

refetch hook method to force refetch

The refetch function is returned as a result property from useQuery or useQuerySubscription hooks. Calling refetch forces refetch of the associated query.

initiate thunk action with forceRefetch option

You can dispatch the initiate thunk action for an endpoint with the option forceRefetch: true to force refetch, producing the same effect as calling refetch().

refetchOnMountOrArgChange accepts boolean or number in seconds

The refetchOnMountOrArgChange property can be passed to an endpoint definition, individual hook calls, or when dispatching initiate (as forceRefetch option). It accepts false (default, uses default behavior), true (always refetch when new subscriber is added), or a number as time in seconds. When a number is provided, at the time a query subscription is created, if there is an existing query in the cache, it compares the current time versus the last fulfilled timestamp. It refetches if the provided number of seconds has elapsed. If no query exists, it fetches the data. If an existing query exists but the specified time has not elapsed, it serves the existing cached data.

refetchOnReconnect option and setupListeners requirement

The refetchOnReconnect option controls whether RTK Query will try to refetch all subscribed queries after regaining a network connection. This requires setupListeners to have been called. If skip: true is specified alongside refetchOnReconnect, the option is not evaluated until skip is false. This option is available on the API definition with createApi and on useQuery, useQuerySubscription, useLazyQuery, and useLazyQuerySubscription hooks.

Force refetch example with refetch and initiate

Example showing two ways to force refetch: calling refetch() returned from useGetPostsQuery, or dispatching api.endpoints.getPosts.initiate({ count: 5 }, { subscribe: false, forceRefetch: true }).

refetchOnMountOrArgChange configuration example

Example showing createApi with refetchOnMountOrArgChange: 30 at the API level, and usage in a component with { refetchOnMountOrArgChange: true } to override the API setting and force refetch on component mount.

refetchOnReconnect configuration and setupListeners example

Example showing createApi with refetchOnReconnect: true at the API level, and setupListeners(store.dispatch) called in the store setup to enable listener behavior.

Enable polling with pollingInterval parameter

To enable polling for a query, pass a pollingInterval parameter to the useQuery hook or action creator with an interval specified in milliseconds. This causes the query to run at the specified interval, creating a 'real-time' effect.

Skip polling when window is out of focus

Pass skipPollingIfUnfocused: true to the useQuery hook or action creator to skip sending requests while the window is out of focus. This requires setupListeners to have been called.

useQuery polling example with skip unfocused

The following example shows how to use polling with the useQuery hook. It automatically refetches every 3 seconds unless the window is out of focus: ```tsx import * as React from 'react' import { useGetPokemonByNameQuery } from './services/pokemon' export const Pokemon = ({ name }: { name: string }) => { const { data, status, error, refetch } = useGetPokemonByNameQuery(name, { pollingInterval: 3000, skipPollingIfUnfocused: true, }) return <div>{data}</div> } ```

Polling without React Hooks using action creator

When using polling with an action creator instead of React Hooks, pass the pollingInterval inside subscriptionOptions to the initiate method: ```ts const { data, status, error, refetch } = store.dispatch( endpoints.getCountById.initiate(id, { subscriptionOptions: { pollingInterval: 3000 }, }), ) ```

Update polling interval manually with updateSubscriptionOptions

When using polling without React Hooks, call updateSubscriptionOptions on the promise ref to update the polling interval. For example, passing pollingInterval: 0 disables polling.

Query hook options: refetch-related options

Query hook options include: refetchOnMountOrArgChange (allows forcing the query to always refetch on mount when true; when a number is provided, refetch if that many seconds have passed since last query, defaults to false), refetchOnFocus (allows forcing the query to refetch when the browser window regains focus, defaults to false), refetchOnReconnect (allows forcing the query to refetch when regaining a network connection, defaults to false). All refetch options override defaults set in createApi.

Give your agent this brain