From 55a6d781146c1bad1521f60ecb3f673a69c66326 Mon Sep 17 00:00:00 2001 From: Alireza Ahmadi Date: Thu, 23 May 2024 12:00:37 +0200 Subject: [PATCH] avoid duplicate api call --- frontend/src/plugins/api.ts | 41 +++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/frontend/src/plugins/api.ts b/frontend/src/plugins/api.ts index f6c7a732..dff99689 100644 --- a/frontend/src/plugins/api.ts +++ b/frontend/src/plugins/api.ts @@ -1,12 +1,29 @@ -import axios from 'axios' +import axios from 'axios'; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest' axios.defaults.baseURL = "./" +const pendingRequests = new Map() axios.interceptors.request.use( (config) => { + // Generate a unique key for the request + const requestKey = `${config.method}:${config.url}` + + // Check if there is already a pending request with the same key + if (pendingRequests.has(requestKey)) { + const cancelSource = pendingRequests.get(requestKey) + cancelSource.cancel('Duplicate request cancelled') + } + + // Create a new cancel token for the request + const cancelSource = axios.CancelToken.source() + config.cancelToken = cancelSource.token + + // Store the cancel token in the pending requests map + pendingRequests.set(requestKey, cancelSource) + if (config.data instanceof FormData) { config.headers['Content-Type'] = 'multipart/form-data' } @@ -15,6 +32,26 @@ axios.interceptors.request.use( (error) => Promise.reject(error), ) +axios.interceptors.response.use( + (response) => { + // Remove the request from the pending requests map + const requestKey = `${response.config.method}:${response.config.url}` + pendingRequests.delete(requestKey) + return response + }, + (error) => { + if (axios.isCancel(error)) { + // Handle duplicate request cancellation here if needed + console.warn(error.message) + } else { + // Remove the request from the pending requests map on error + const requestKey = `${error.config.method}:${error.config.url}` + pendingRequests.delete(requestKey) + } + return Promise.reject(error) + } +); + const api = axios.create() -export default api \ No newline at end of file +export default api