redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

How to set `extra` when use RTK query hooks?

Open sentoc opened this issue 1 year ago • 1 comments

Background

I'd like to determine baseUrl when make the actual api call.

baseUrl is just for example, in some cases, you may want to make the final decision when calling api, instead of at api definition time.

by reading https://github.com/reduxjs/redux-toolkit/issues/1335, I know we can use extra field, something like:

// customize a base query
export const myBaseQuery = (
  args,
  { dispatch, getState, extra },
  extraOptions,
) => {
  // determine baseUrl by `region`, which passed in via `extra`
  // we can also read config information from store via getState.
  const baseUrl = getBaseUrlByRegion(extra.region);

  // do more things with baseUrl
};

// declare myApi and endpoints
export const myApi = createApi({
  reducerPath: 'myApi',
  baseQuery: myBaseQuery,
  endpoints: builder => ({
    // getPostById only cares about `id`,
    // so I do not want to pass `region` as additional args here. 
    getPostById: builder.query<any, number>({
      query: id => ({
        url: `posts/${id}`,
        method: 'GET',
      }),
    }),
  }),
});

Question

Its ok to define apis as above, but I cannot find a way to set the extra when use query hooks, below code is what I want, but does not work, any suggestion is appreciated!

// while inside a component
// want to set `extra` when useQuery/useLazyQuery/useMutation,
// so any further calls to `getPostById` will contains the `region` information,
// but those hooks does not accept `extra` args.
const [getPostById, { data }] = myApi.endpoints.getPostById.useLazyQuery(
  { region: 'us' },  // does not work here
);

// expected clean call
const postInUsRegion = getPostById(12);

More

  • We do able to do as below, but we need to add region to all my endpoints, even though those endpoints does not care about the parameter.
const [getPostById, { data }] = myApi.endpoints.getPostById.useLazyQuery()

// unexpected, because parameter `region` is not part of the api.
const postInSgRegion = getPostById({postId: 12, region: 'sg'})
  • Also tried dispatch, still not able to pass extra in.
const promise = dispatch(api.endpoints.getPosts.initiate(12), { region: 'us' })
  • I read the test case from PR https://github.com/reduxjs/redux-toolkit/pull/1378/commits/f73e4bcaf333b48487841d976b5f782e3d1176ff, but its just set extra at middleware level globally, not per hook call.
test('passes the extraArgument property to the baseQueryApi', async () => {
  const baseQuery = (_args: any, api: BaseQueryApi) => ({ data: api.extra })
  const api = createApi({
    baseQuery,
    endpoints: (build) => ({
      getUser: build.query<unknown, void>({
        query: () => '',
      }),
    }),
  })
  const store = configureStore({
    reducer: {
      [api.reducerPath]: api.reducer,
    },
    middleware: (gDM) =>
      gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),
  })
  const { getUser } = api.endpoints
  const { data } = await store.dispatch(getUser.initiate())
  expect(data).toBe('cakes')
})

sentoc avatar Apr 17 '24 13:04 sentoc