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,
}
})
},
}),
}),
});
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 autoplete ponent to pick multiple filters. Any ideas?
Share Improve this question asked Dec 30, 2022 at 11:11 DorinDorin 651 silver badge9 bronze badges1 Answer
Reset to default 7RTK 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 p of Complexities) {
params.append('Complexities', p )
}
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' }),
})