Search code examples
redux-toolkitrtk-query

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?


Solution

  • 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']
    }),