Back

Technologies:

javascriptjavascript
avatar
Tolerim
24 days ago

What is the method for passing an array as parameters in React Query?

Here is the modified paragraph: My react query API has infinite scrolling. However, there is an issue with the array of parameters. If I send these parameters, the API link becomes:

https://api/filter?jobStatus[]=NEW&jobStatus[]=IN&page=0&size=20
Instead, the API should look like this:

https://api/filter?jobStatus=NEW&jobStatus=IN&page=0&size=20
Can anyone suggest a solution to fix this problem?

EDIT:

I attempted to use the paramSerializer, but it caused all of my APIs to stop working. Here's my API code:


const axiosInstance = axios.create({
  baseURL: 'api',
  headers: {
    'Content-Type': 'application/json',
  },
  
});

export default axiosInstance;
Answers(2)
avatar
Vogi
23 days ago
Verified Answer
You can use the paramsSerializer option in axios to serialize the array of parameters. Here's an example:
const axiosInstance = axios.create({
  baseURL: 'api',
  headers: {
    'Content-Type': 'application/json',
  },
  paramsSerializer: function (params) {
    return qs.stringify(params, {arrayFormat: 'repeat'})
  }
});

export default axiosInstance;
This will result in the API link looking like this:
I hope this helps! Let me know if you have any other questions.

Sources

React infinite-scroll with array from hook state - Stack OverflowHow to implement infinite scroll using react query for NewsApiHow to achieve Infinite scroll in React with React Query?react-infinite-scroll-component load more with arrayHow to Implement Infinite Scrolling with React.js | Pluralsight
avatar
Tolerim
24 days ago
To fix the array of params issue, you can pass a custom paramsSerializer function to axios.create() method. Here's an example code snippet:
const axiosInstance = axios.create({
  baseURL: 'api',
  headers: {
    'Content-Type': 'application/json',
  },
  paramsSerializer: function(params) {
    // This function will convert the array-based params to comma-separated values
    return qs.stringify(params, {arrayFormat: 'comma'});
  },
});

export default axiosInstance;
In the code above, we have used the qs library to stringify the params object with the arrayFormat option set to comma. This will convert the array-based params to comma-separated values in the API query string. Note that you need to install and import the qs library in your project for this to work. You can install it using a package manager like npm or yarn.
;