Requirement description:
The page performs continuous click operations on buttons. Although the front-end adds a loading effect to the button, it is found that if the click speed is very fast, the loading effect will not have time to assign a value and be executed. At this time, continuous interface calls will occur, causing Errors in data saving or process data or duplicate data addition.
At this time, use anti-shake to solve the problem.
The package is as follows:
import { request as iceRequest } from 'ice';
import _ from 'lodash';
function debounceAsync(func, wait) {
let timeout;
return async function (...args) {
clearTimeout(timeout);
return new Promise((resolve) => {
timeout = setTimeout(async () => {
const result = await func(...args);
resolve(result);
}, wait);
});
};
}
const request = (url: string, option) => {
if (option.method) {
if (option.method.toUpperCase() === 'GET' && option.query) {
option.params = option.query;
}
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(option.method.toUpperCase()) && option.query) {
option.data = option.query;
}
}
return iceRequest({
url,
...option,
});
};
const debounceRequestFn = (url: string, option, delay = 500) => {
if (option.method) {
if (option.method.toUpperCase() === 'GET' && option.query) {
option.params = option.query;
}
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(option.method.toUpperCase()) && option.query) {
option.data = option.query;
}
}
return iceRequest({
url,
...option,
});
};
export default request;
const debounceRequest = debounceAsync(async function (url: string, option, delay = 500) {
const response = await debounceRequestFn(url, option, delay);
return response
}, 300)
export {
debounceRequest
}
Then just reference the method in the page
import request from '@/utils/request';
import debounceRequest from '@/utils/request';