Skip to content

v2.7.0

Latest
Compare
Choose a tag to compare
@markerikson markerikson released this 16 Apr 17:55

RTK has hit Stage 2.7! 🤣 This feature release adds support for Standard Schema validation in RTK Query endpoints, fixes several issues with infinite queries, improves perf when infinite queries provide tags, adds a dev-mode check for duplicate middleware, and improves reference stability in slice selectors and infinite query hooks.

Changelog

Standard Schema Validation for RTK Query

Apps often need to validate responses from the server, both to ensure the data is correct, and to help enforce that the data matches the expected TS types. This is typically done with schema libraries such as Zod, Valibot, and Arktype. Because of the similarities in usage APIs, those libraries and others now support a common API definition called Standard Schema, allowing you to plug your chosen validation library in anywhere Standard Schema is supported.

RTK Query now supports using Standard Schema to validate query args, responses, and errors. If schemas are provided, the validations will be run and errors thrown if the data is invalid. Additionally, providing a schema allows TS inference for that type as well, allowing you to omit generic types from the endpoint.

Schema usage is per-endpoint, and can look like this:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import * as v from 'valibot'

const postSchema = v.object({
  id: v.number(),
  name: v.string(),
})
type Post = v.InferOutput<typeof postSchema>

const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints: (build) => ({
    getPost: build.query({
      // infer arg from here
      query: ({ id }: { id: number }) => `/post/${id}`,
      // infer result from here
      responseSchema: postSchema,
    }),
    getTransformedPost: build.query({
      // infer arg from here
      query: ({ id }: { id: number }) => `/post/${id}`,
      // infer untransformed result from here
      rawResponseSchema: postSchema,
      // infer transformed result from here
      transformResponse: (response) => ({
        ...response,
        published_at: new Date(response.published_at),
      }),
    }),
  }),
})

If desired, you can also configure schema error handling with the catchSchemaFailure option. You can also disable actual runtime validation with skipSchemaValidation (primarily useful for cases when payloads may be large and expensive to validate, but you still want to benefit from the TS type inference).

See the "Schema Validation" docs section in the createApi reference and the usage guide sections on queries, infinite queries, and mutations, for more details.

Infinite Query Fixes

This release fixes several reported issue with infinite queries:

  • The lifecycleApi.updateCachedData method is now correctly available
  • The skip option now correctly works for infinite query hooks
  • Infinite query fulfilled actions now include the meta field from the base query (such as {request, response}). For cases where multiple pages are being refetched, this will be the meta from the last page fetched.
  • useInfiniteQuerySubscription now returns stable references for refetch and the fetchNext/PreviousPage methods

upsertQueryEntries, Tags Performance and API State Structure

We recently published a fix to actually process per-endpoint providedTags when using upsertQueryEntries. However, this exposed a performance issue - the internal tag handling logic was doing repeated O(n) iterations over all endpoint+tag entries in order to clear out existing references to that cache key. In cases where hundreds or thousands of cache entries were being inserted, this became extremely expensive.

We've restructured the state.api.provided data structure to handle reverse-mapping between tags and cache keys, which drastically improves performance in this case. However, it's worth noting that this is a change to that state structure. This shouldn't affect apps, because the RTKQ state is intended to be treated as a black box and not generally directly accessed by user app code. However, it's possible someone may have depended on that specific state structure when writing a custom selector, in which case this would break. An actual example of this is the Redux DevTools RTKQ panel, which iterates the tags data while displaying cache entries. That did break with this change. Prior to releasing RTK 2.7,we released Redux DevTools 3.2.10, which includes support for both the old and new state.api.provided definitions.

TS Support Matrix Updates

Following with the DefinitelyTyped support matrix, we've officially dropped support for TS 5.0, and currently support TS 5.1 - 5.8. (RTK likely still works with 5.0, but we no longer test against that in CI.)

Duplicate Middleware Dev Checks

configureStore now checks the final middleware array for duplicate middleware references. This will catch cases such as accidentally adding the same RTKQ API middleware twice (such as adding baseApi.middleware and injectedApi.middlweware - these are actually the same object and same middleware).

Unlike the other dev-mode checks, this is part of configureStore itself, not getDefaultMiddleware().

This can be configured via the new duplicateMiddlewareCheck option.

Other Changes

createEntityAdapter now correctly handles adding an item and then applying multiple updates to it.

The generated combineSlices selectors will now return the same placeholder initial state reference for a given slice, rather than returning a new initial state reference every time.

useQuery hooks should now correctly refetch after dispatching resetApiState.

What's Changed

Full Changelog: v2.6.1...v2.7.0