Home > Software design >  How to build the url with filter params in RTK Query of this format?
How to build the url with filter params in RTK Query of this format?

Time:12-31

I struggle making the url to fetch data with filters. Backend REST api is built in .Net. The url to filter items has this format:

BASE_URL/ENDPOINT?Technologies=some-id&Complexities=0&Complexities=1&page=1&pageSize=3

Technologies and Complexities can repeat x times with different values.

RTK Query provides a query function, but it doesn't build up the url in the way i need.

export const apiService = createApi({
  reducerPath: 'apiService',
  baseQuery: fetchBaseQuery({ baseUrl: BASE_URL }),
  endpoints: (build) => ({
    getAllQuizzes: build.query<ApiResponse, QueryProps>({
      query: ({ Technologies, Complexities, page, pageSize }) => {
        return ({
          url: ENDPOINT,
          params: {
            Technologies,
            Complexities,
            page,
            pageSize, 
          }
        })
      },
    }),
  }),
});

Im using mui async autocomplete component to pick multiple filters. Any ideas?

CodePudding user response:

RTK Query only uses the object signature of the URLSearchParams constructor function by default.

For you, that will not work.

Theoretically, you could pass in your own pre-populated URLSearchParams object in there (but this is not a guarantee for future versions and not indicated by the TypeScript types), or could just omit the params step altogether, building the full url yourself:

   getAllQuizzes: build.query<ApiResponse, QueryProps>({
      query: ({ Technologies, Complexities, page, pageSize }) => {
        const params = new URLSearchParams({ page, pageSize })
        for (const tech of Technologies) {
          params.append('Technologies', tech)
        }
        for (const comp of Complexities) {
          params.append('Complexities', comp )
        }
        return ({
          url: ENDPOINT '?' params.toString(),
        })
      },
    }),

Alternatively, you could also keep your existing code and specify a custom paramsSerializer function - for example the query-string library:

import queryString from 'query-string'

//...
const baseQuery = fetchBaseQuery({
    baseUrl,
    paramsSerializer: (params: Record<string, unknown>) =>
        queryString.stringify(params, { arrayFormat: 'none' }),
})
  • Related