detinu20
detinu20

Reputation: 319

RTK Query url with parameter which is an array

I am currently trying to pass in an array to a query which will be used as parameters but keeping encountering an issue that the object doesn't seem to take an array in the parameters and doesn't format the url param string as I need.

Here is my array that is passed into my RTK hook:

filterArguments = [1,2]

RTK Query:

getFood: builder.query({
  // The URL for the request is '/fakeApi/posts'
  query: (filterArguments) => ({
    url:'/user/food/',
    params: {
      ...filterArguments
    }

  }),
  
  providesTags:['Food']


}),

This is bringing back an error or if i fiddle around with it an send an object through it brings back the following URL ignoring other items in the object of the same name:

test:8000/api/?filter=1 

However this is not the desired result, the desire url result from passing an array of filter id's would be:

test:8000/api/?filter[]=1&filter[]=2

is this achievable in RTK query? and how would i achieve this?

Upvotes: 3

Views: 4931

Answers (2)

Sarthak Saklecha
Sarthak Saklecha

Reputation: 237

use paramSerializer in rtk query -

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

// Custom paramsSerializer function for query parameter serialization
const paramsSerializer = (params: Record<string, any>): string => {
  const searchParams = new URLSearchParams();

  for (const key in params) {
    const value = params[key];

    if (Array.isArray(value)) {
      // Serialize arrays with the '[]' notation
      value.forEach((item) => {
        searchParams.append(`${key}[]`, item);
      });
    } else {
      // Serialize other values
      searchParams.append(key, value);
    }
  }

  return searchParams.toString();
};

// Create the RTK Query API
export const api = createApi({
  // Configure the base query with the custom paramsSerializer
  baseQuery: fetchBaseQuery({ baseUrl: '/api', paramsSerializer }),
  endpoints: (builder) => ({
    // Define the getClients mutation endpoint
    getClients: builder.mutation<
      { clients: Client[] },
      {
        serviceProviderId: string;
        body: {
          ids?: string[];
          name?: string;
          phoneNumber?: string;
          email?: string;
        };
      }
    >({
      query: ({ serviceProviderId, body }) => ({
        // Specify the URL, method, and params using the body object
        url: `/${serviceProviderId}/clients`,
        method: 'GET',
        params: body,
      }),
    }),
  }),
});

Upvotes: 1

Rashomon
Rashomon

Reputation: 6762

redux-toolkit doesnt implement any special http library. It uses fetch under the hood. For params, it uses URLSearchParams(). So the API will be similar. Since URLSearchParams() doesnt support your params notation, you can use the query-string library:

const queryString = require('query-string');

getFood: builder.query({
  query: (filterArguments) => ({
    url:'/user/food/' + queryString.stringify({filter: filterArguments}, {arrayFormat: 'bracket'}),
  }),
  providesTags:['Food']
}),

Upvotes: 5

Related Questions