javascriptreact-nativeaxios

Run multiple axios requests at the same time and produce only one request to the backend


Is it possible for multiple axios requests to run at the same time and produce only one request to the backend?

Here's what i'm trying to do in my interceptor but i'm stuck:

instance.interceptors.request.use((request: AxiosRequestConfig) => {
        return new Promise((resolve, reject) => {
            if (timeout) {
                clearTimeout(timeout);
            }

            let ids: any[] = [];
            temp_id = [...temp_id, request.params];
            queue = [...queue, request];

            timeout = setTimeout(async () => {
                const output = await temp_id.map(e => e['ids'])
                await output.map(r => {
                    ids = Array.from(new Set(ids.concat(r)));
                });

                const config: AxiosRequestConfig = {
                    ...request,
                    baseURL: request.baseURL,
                    headers: request.headers,
                    params: { ids }
                };

                resolve(config);
            }, 1000);
        })
        // return request;
    }, (err) => Promise.reject(err))

Expectations:

Let's assume we make this 2 requests, i want to intercept the request, merge the params and send out just one request to the server with the new params.

const uri = "/uri";
    let a = api.get(uri, {params: { ids: [0,1,2] }});
    let b = api.get(uri, {params: { ids: [2,3] }});
    return Promise.all([a, b])
        .then(e => console.log(e))
        .catch(err => console.log(err.response))

Output:

At the interceptor I should be able to filter through the params and send out a single request to the server:

   const output = await temp_id.map(e => e['ids'])
   await output.map(r => {
       ids = Array.from(new Set(ids.concat(r)));
   });

   //send out a single request with params { ids: [0,1,2,3] }

Solution

  • I fixed this by debouncing the function that makes the api request. Find example below:

    const oldData = [1, 2, 3]
    const funcMakingApiRequest = _debounce(
       (currData) => {
         const payload = [...oldData, ...currData]
         // make axios request with payload after debounce
       },
       500,
       {
         leading: true,
         trailing: false,
       }
     )