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

How to prepate query parameters for rtk-query endpoints?

Open TechSaq opened this issue 3 years ago • 2 comments

Is there a way to transform the query parameters which are passed to endpoints?

I want to add default values in case query parameters is missing any.

TechSaq avatar Aug 25 '22 16:08 TechSaq

Can you provide some endpoint definition so we know we're thinking of the same thing?

litera avatar Aug 25 '22 17:08 litera

Let's say i have the following getPosts endpoint definition which takes query arguments.

const apiSlice = createApi({
  ...
  endpoints: (builder) => ({
    getPosts: builder.query({
      query: (payload) =>({
          url: "posts/search",
          method: "POST",
          body: payload
       })
    }),
  ...
})

Following is the payload passed to query hook. What I want is I just want to pass{searchText: "some text"}in query hooks as payload and other payload default values get merged before payload is passed to query.

const payload = {
  ids: [],
  searchText: "",
  pageIndex: 0,
  pageSize: 10
}
const {data} = useGetPostsQuery(payload);

I can write a helper or define a payload with default values and then destructor both default payload and query payload inside the endpoint like this.

const apiSlice = createApi({
  ...
  endpoints: (builder) => ({
    getPosts: builder.query({
      query: (payload) => {
           const mergedPayload = {
              ...defaultPayload,
              ...payload
           }

          return {
             url: "posts/search",
             method: "POST",
             body: mergedPayload
         }
       }
    }),
  ...
})

But doing this, cache result will be stored only with passed payload. Is it possible to transform the payload before it is passed to enpoint?

Currently I have written a helper function which take passed payload and combine the default values with the passed payload and return the merged payload with all default values in case any property is not passed.

const newPayload = preparePayload(payload);
const {data} = useGetPostsQuery(newPayload);

But I have to do this at every place wherever I have to call the query hook. It would be better if rtk-query has some kind of api which can transform the payload at single place inside createApi similar to transformResponse api

Hope I am able to make my point.

TechSaq avatar Aug 26 '22 02:08 TechSaq