Skip to content

Commit

Permalink
avoid duplicate api call
Browse files Browse the repository at this point in the history
  • Loading branch information
alireza0 committed May 23, 2024
1 parent caa115b commit 55a6d78
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions frontend/src/plugins/api.ts
Original file line number Diff line number Diff line change
@@ -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'
}
Expand All @@ -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
export default api

0 comments on commit 55a6d78

Please sign in to comment.