Search code examples
javascriptreact-query

How can I send an array params in React Query?


This is my react query api scroll with infinite scroll

export function useGetEmployeesInfiniteScroll() {
  return useInfiniteQuery(
    [QUERY_KEYS.employees],
    async ({ pageParam = 0 }) => {
      const { data } = await axiosInstance.get(v1 + employees + filter, {
        params: {
          jobStatus: ['NEW', 'IN'],
          page: pageParam,
          size: 20,
        },
      });
      return data;
    },
    {
      getNextPageParam: (lastPage) => {
        const nextPage = lastPage.number + 1;
        return nextPage < lastPage.totalPages ? nextPage : undefined;
      },
    },
  );
}

The problem is an array of params. If I send these parameters, the API link is

https://api/filter?jobStatus[]=NEW&jobStatus[]=IN&page=0&size=20

The API must be like this

https://api/filter?jobStatus=NEW&jobStatus=IN&page=0&size=20

How can I fix it?


Solution

  • You need to use the paramsSerializer option of axios.

    qs package is quite helpful here

    await axiosInstance.get('<url>', {
      params: {
        ...
      },
      paramsSerializer: params => {
        return qs.stringify(params , { indices: false })
      }
    })
    

    You can also try arrayFormat parameter while serializing with qs

    qs.stringify(params, { arrayFormat: 'repeat' })