Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update infinite query draft PR to separate PageParams type #4674

Draft
wants to merge 31 commits into
base: master
Choose a base branch
from

Conversation

markerikson
Copy link
Collaborator

@markerikson markerikson commented Oct 23, 2024

This PR is a copy of the "Infinite Query API" draft PR in #4393 , but with (currently) one additional commit that tries to modify the infinite query endpoint definitions to add a separate PageParam TS generic and pass it through:

Background

With the current implementation in #4393, the QueryArg type gets used as the type for the pageParam field. That results in an awkward usage pattern, because there's a conflation between "the arg we use to generate the cache key" vs "the value we need to define the next page to fetch".

What I think we want is to specify builder.infiniteQuery<ReturnType, QueryArg, PageParam>(). What we should end up with is a cached data structure of {pages: ReturnType[], pageParams: PageParam[]}.

We also should then override the normal query endpoint types so that we end up with query: (arg: PageParam), but keep the external behavior of initiate(arg: QueryArg).

I could be wrong on all this, but this seems like it makes sense to my admittedly-confused brain.

Current WIP

In 3f0b35f , I've successfully threaded a PageParam generic through all the layers of our endpoint definitions. Where I'm stuck is getting that split behavior between the type of arg in initiate() vs the type of arg in query().

In infiniteQueries.test.tsx, I have this example code:

    const pokemonApi = createApi({
      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
      endpoints: (builder) => ({
        // GOAL: Specify both the query arg (for cache key serialization)
        // and the page param type (for feeding into the query URL)
        getInfinitePokemon: builder.infiniteQuery<Pokemon[], string, number>({
          infiniteQueryOptions: {
            getNextPageParam: (
              lastPage,
              allPages,
              // ✅Currently: page param type is `number`
              lastPageParam,
              allPageParams,
            ) => lastPageParam + 1,
          },
          // ❌ This seems to be controlled by `BaseEndpointDefinition`
          // GOAL: should be `pageParam: number`
          query(pageParam) {
            return `https://example.com/listItems?page=${pageParam}`
          },
        }),
      }),
    })

    const res = storeRef.store.dispatch(
      // ❌ This seems to be controlled by `BaseEndpointDefinition`.
      // GOAL: should be `arg: string`
      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
    )

It looks like the behavior is ultimately controlled by our BaseEndpointDefinition type. The existing implementation is:

// ❌Existing logic:
// - ✅ `initiate(arg: string)
// - ❌ `query(pageParam: string)
export type BaseEndpointDefinition<
  QueryArg,
  BaseQuery extends BaseQueryFn,
  ResultType,
> = (
  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
      ? never
      : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>)
  | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>
)

I've tried three other variations, each of which fails in a different way:

// GOAL: if `PageParam` is supplied, then we should
// pass it through so that it becomes the argument type
// for `query` and `queryFn`.
// Otherwise, we stick with `QueryArg`.
// However, `initiate` should always receive`QueryArg`.

// ❌ Failing change 1: use `FinalQueryArg`:
// - ❌ `initiate(arg: number)
// -  ✅`query(pageParam: number)
export type BaseEndpointDefinition<
  QueryArg,
  BaseQuery extends BaseQueryFn,
  ResultType,
  PageParam = never,
  FinalQueryArg = [PageParam] extends [never] ? QueryArg : PageParam,
> = (
  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
      ? never
    : EndpointDefinitionWithQuery<FinalQueryArg, BaseQuery, ResultType>)
  | EndpointDefinitionWithQueryFn<FinalQueryArg, BaseQuery, ResultType>
// ❌ Failing change 2: one nested `PageParam` checks:
// - ❌ `initiate(arg: string | number)
// - ✅ `query(pageParam: number)`
export type BaseEndpointDefinition<
  QueryArg,
  BaseQuery extends BaseQueryFn,
  ResultType,
  PageParam = never,
> = (
  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
     ? never
       : [PageParam] extends [never]
         ? EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>
         : EndpointDefinitionWithQuery<PageParam, BaseQuery, ResultType>)
  : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>
// ❌ Failing change 3: both nested `PageParam` checks:
// - ❌ `initiate(arg: unknown)
// - ❌ `query(pageParam: any)`, field is `undefined`
export type BaseEndpointDefinition<
  QueryArg,
  BaseQuery extends BaseQueryFn,
  ResultType,
  PageParam = never,
> = (
  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
     ? never
       : [PageParam] extends [never]
         ? EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>
         : EndpointDefinitionWithQuery<PageParam, BaseQuery, ResultType>)
  : [PageParam] extends [never]
    ? EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>
    : EndpointDefinitionWithQuery<PageParam, BaseQuery, ResultType>

(I had to reconstruct those types by hand in this PR description - I probably made a typo somewhere, but hopefully it's clear what I'm going for)

riqts and others added 30 commits October 22, 2024 15:36
This reverts commit 4089f11
Copy link

codesandbox bot commented Oct 23, 2024

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

Copy link

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 3f0b35f:

Sandbox Source
@examples-query-react/basic Configuration
@examples-query-react/advanced Configuration
@examples-action-listener/counter Configuration
rtk-esm-cra Configuration

Copy link

netlify bot commented Oct 23, 2024

Deploy Preview for redux-starter-kit-docs ready!

Name Link
🔨 Latest commit 3f0b35f
🔍 Latest deploy log https://app.netlify.com/sites/redux-starter-kit-docs/deploys/6719103e3490f300088aa267
😎 Deploy Preview https://deploy-preview-4674--redux-starter-kit-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

size-limit report 📦

Path Size
1. entry point: @reduxjs/toolkit/query/react (modern.mjs) 14.16 KB (+4.55% 🔺)
1. entry point: @reduxjs/toolkit/query (cjs, production.min.cjs) 23.07 KB (+3.11% 🔺)
1. entry point: @reduxjs/toolkit/query/react (cjs, production.min.cjs) 25.47 KB (+4.46% 🔺)
2. entry point: @reduxjs/toolkit/query (without dependencies) (cjs, production.min.cjs) 9.81 KB (+6.92% 🔺)
2. entry point: @reduxjs/toolkit/query/react (without dependencies) (cjs, production.min.cjs) 3.28 KB (+16.35% 🔺)
3. createApi (.modern.mjs) 14.56 KB (+4.45% 🔺)
3. createApi (react) (.modern.mjs) 16.74 KB (+7.17% 🔺)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants