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 · API · all subjects

otherexports

103 notes in this subject, read out of this brain and free to use. This is page 2 of 2.

SerializedError interface

SerializedError has optional properties: code (string), message (string), name (string), stack (string).

createReducer function signature

createReducer has two overloads: (1) createReducer<S extends NotFunction<any>>(initialState: S | (() => S), builderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>, and (2) createReducer<S extends NotFunction<any>, CR extends CaseReducers<S, any> = CaseReducers<S, any>>(initialState: S | (() => S), actionsMap: CR, actionMatchers?: ActionMatcherDescriptionCollection<S>, defaultCaseReducer?: CaseReducer<S>): ReducerWithInitialState<S>.

MiddlewareArray class methods

MiddlewareArray<Middlewares extends Middleware<any, any>> extends Array and has methods: concat (two overloads accepting AdditionalMiddlewares array or spread), prepend (two overloads accepting AdditionalMiddlewares array or spread). Both methods return MiddlewareArray with combined middleware types.

createSerializableStateInvariantMiddleware function

createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware. Returns middleware that checks for non-serializable values in state.

getType function

getType<T extends string>(actionCreator: PayloadActionCreator<any, T>): T. Extracts the type string from a PayloadActionCreator.

findNonSerializableValue function

findNonSerializableValue(value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: readonly (string | RegExp)[]): NonSerializableValue | false. Finds non-serializable values in an object tree.

isPlain and isPlainObject functions

isPlain(val: any): boolean checks if a value is plain. isPlainObject(value: unknown): value is object checks if a value is a plain object.

isImmutableDefault function

isImmutableDefault(value: unknown): boolean. Default function for checking if a value is immutable (used in immutability middleware).

ActionCreatorWithOptionalPayload interface

ActionCreatorWithOptionalPayload<P, T> extends BaseActionCreator<P, T> and is callable as (payload?: P): PayloadAction<P, T>.

ActionCreatorWithoutPayload interface

ActionCreatorWithoutPayload<T> extends BaseActionCreator<undefined, T> and is callable as (): PayloadAction<undefined, T>.

ActionCreatorWithNonInferrablePayload interface

ActionCreatorWithNonInferrablePayload<T> extends BaseActionCreator<unknown, T> and is callable as <PT extends unknown>(payload: PT): PayloadAction<PT, T>.

ActionCreatorWithPreparedPayload interface

ActionCreatorWithPreparedPayload<Args, P, T, E, M> extends BaseActionCreator<P, T, M, E> and is callable as (...args: Args): PayloadAction<P, T, M, E>.

reducerPath property of API slice

The reducerPath property is a string that contains the reducerPath option provided to createApi. Use this as the root state key when adding the reducer function to the store so that the rest of the generated API logic can find the state correctly.

reducer property of API slice

The reducer property of an API slice is a standard Redux slice reducer function containing the logic for updating the cached data. Add this to the Redux store using the reducerPath as the root state key.

middleware property of API slice

The middleware property of an API slice is a custom Redux middleware that contains logic for managing caching, invalidation, subscriptions, polling, and more. Add this to the store setup after other middleware.

createAction generates action creator with toString

createAction() generates an action creator function for the given action type string. The function itself has toString() defined, so that it can be used in place of the type constant.

ApiProvider component props

ApiProvider accepts props object with the following properties: children (required, any), api (required, type A extends Api<any, {}, any, any>), setupListeners (optional, same parameters as setupListeners function's second parameter), and context (optional, Context<ReactReduxContextValue | null>). Returns JSX.Element.

createApi function signature and options

createApi is a function that takes CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>. The options include: baseQuery (required, BaseQueryFn), endpoints (required, function receiving EndpointBuilder and returning Definitions), keepUnusedDataFor (optional, number), reducerPath (optional, ReducerPath, default 'api'), refetchOnFocus (optional, boolean), refetchOnMountOrArgChange (optional, boolean or number), refetchOnReconnect (optional, boolean), serializeQueryArgs (optional, SerializeQueryArgs<unknown>), and tagTypes (optional, readonly array of TagTypes).

fetchBaseQuery function signature and return type

fetchBaseQuery takes an optional object parameter with properties baseUrl, prepareHeaders, fetchFn, and additional baseFetchOptions. It returns BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>.

BaseQueryFn type signature

BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> is a function type that takes args, api (BaseQueryApi), and extraOptions (DefinitionExtraOptions), and returns MaybePromise<QueryReturnValue<Result, Error, Meta>>.

reactHooksModule function signature

reactHooksModule is a function that takes an optional ReactHooksModuleOptions object with properties batch, useDispatch, useSelector, and useStore. It returns Module<ReactHooksModule>.

retry base query enhancer

retry is a BaseQueryEnhancer<unknown, StaggerOptions, void | StaggerOptions> with an additional fail property of type typeof fail_2. It can be used to enhance a base query with automatic retry logic.

buildCreateApi function signature

buildCreateApi takes a spread of Module types (at least one: Modules extends [Module<any>, ...Module<any>[]]) and returns CreateApi<Modules[number]['name']>. This is used to build a custom createApi function with specified modules.

coreModule constant

coreModule is a constant that is a function returning Module<CoreModule>. It provides the core RTK Query module functionality.

fakeBaseQuery function

fakeBaseQuery<ErrorType>() is a function that takes a type parameter for error type and returns BaseQueryFn<void, NEVER, ErrorType, {}>. It is useful for testing or creating API definitions without actual network calls.

copyWithStructuralSharing function

copyWithStructuralSharing<T>(oldObj: any, newObj: T): T is a function that copies an object while preserving structural sharing, used internally by RTK Query for optimized state updates.

FetchBaseQueryError interface properties

FetchBaseQueryError is an interface with two properties: data (unknown) and status (number). This represents an error returned by fetchBaseQuery.

setupListeners function signature

setupListeners is exported as a public function with signature: (dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: { onFocus: typeof onFocus, onFocusLost: typeof onFocusLost, onOnline: typeof onOnline, onOffline: typeof onOffline }) => () => void): () => void. It sets up event listeners for online/offline and focus/blur events and returns an unsubscribe function.

setupListeners necessity and behavior

setupListeners is necessary to enable automatic refetching on window focus, reconnection, and online events. The function takes a dispatch function and optional custom handler, and returns an unsubscribe function. When called without a custom handler, it uses default actions for onFocus, onFocusLost, onOnline, and onOffline events.

skipToken constant

skipToken is exported as a public constant of type unique symbol, used to skip execution of a query or mutation.

SkipToken type

SkipToken is a type alias defined as typeof skipToken, representing the type of the skipToken symbol.

skipSelector deprecated constant

skipSelector is exported as a public deprecated constant of type symbol, replaced by skipToken.

RTK Query setup with createApi, fetchBaseQuery, and store integration

To set up RTK Query, import createApi and fetchBaseQuery from '@reduxjs/toolkit/query/react'. Create an API instance with createApi, passing reducerPath, baseQuery created from fetchBaseQuery with baseUrl, tagTypes array, and endpoints function. Add the API reducer and middleware to the store via configureStore: the reducer is accessed via api.reducerPath and api.reducer, and middleware is added via getDefaultMiddleware().concat(api.middleware). Export the generated hooks from the API instance (e.g., useGetPostsQuery, useAddPostMutation).

createApi configuration structure

createApi accepts an object with the following properties: reducerPath (string), baseQuery (created from fetchBaseQuery), tagTypes (array of tag names), and endpoints (function that receives build object and returns object with endpoint definitions). The build object has query() and mutation() methods for defining endpoints.

Query and mutation endpoint definitions

Query endpoints are defined with build.query<ResponseType, ArgType>() taking an object with query property (function returning URL string or request config) and optional providesTags property (function receiving result and returning tag array). Mutation endpoints are defined with build.mutation<ResponseType, ArgType>() taking an object with query property and optional invalidatesTags property (function receiving result, error, and arguments, returning tag array) and optional onQueryStarted lifecycle handler.

Tag-based cache invalidation pattern

Tags are used for cache invalidation instead of manual patching. Query endpoints provide tags via providesTags callback, returning an array of tag objects with type and optional id properties. Mutation endpoints invalidate tags via invalidatesTags callback. When tags are invalidated, all actively subscribed queries providing those tags are refetched automatically.

Optimistic updates in mutation lifecycle

Optimistic updates are performed in the onQueryStarted async handler of a mutation endpoint. The handler receives the mutation arguments and an object with dispatch and queryFulfilled properties. Use dispatch(api.util.updateQueryData(queryName, args, updateFunction)) to patch cache before the request completes. The updateFunction receives a draft (Immer-wrapped) and can modify it directly. Wrap this in a try-catch where the catch block calls patch.undo() to revert on failure after awaiting queryFulfilled.

Use injectEndpoints to extend a single API instance

To split endpoints across files while maintaining one API slice per base URL, create a base API with createApi and endpoints returning an empty object, then call api.injectEndpoints() in other files, passing endpoints function. This preserves cache invalidation behavior across all endpoints and avoids duplicating middleware.

Critical mistake: creating multiple API slices for one backend

Never create multiple createApi instances for the same backend. This breaks invalidation behavior because each API slice has its own cache and middleware. Instead, create one API slice and use api.injectEndpoints() in other files to add endpoints.

Critical mistake: forgetting api.reducer or api.middleware in store

Both api.reducer and api.middleware must be added to the store for RTK Query to function. The reducer manages cache state and must be added via configureStore reducer object keyed by api.reducerPath. The middleware must be added via middleware option using getDefaultMiddleware().concat(api.middleware). Without both, hooks will not work properly.

Do not persist RTK Query cache by default

Persisting RTK Query cache to browser storage (like localStorage) by default keeps stale data around longer than users expect. Treat cache persistence as a special case opt-in, not the default behavior.

Do not patch cache from components

Avoid dispatching api.util.updateQueryData from component useEffect hooks. Cache patches must stay coupled to mutation lifecycles via onQueryStarted handlers so optimistic updates and rollback logic remain together with the request they modify.

Invalidation only refetches actively subscribed queries

Invalidation with api.util.invalidateTags() only triggers refetch for queries that are currently subscribed (actively used by components). If a query's subscription is removed before invalidation occurs, the cache entry is dropped and the query must be initiated again to trigger a new fetch.

Give your agent this brain