Debounce storage calls on http intercept

This commit is contained in:
Jake McDermott 2020-09-29 12:56:52 -04:00
parent 5ccee4aea2
commit 838a3822a5
No known key found for this signature in database
GPG Key ID: 0E56ED990CDFCB4F
3 changed files with 66 additions and 2 deletions

View File

@ -2,6 +2,12 @@ import axios from 'axios';
import { SESSION_TIMEOUT_KEY } from '../constants';
import { encodeQueryString } from '../util/qs';
import debounce from '../util/debounce';
const updateStorage = debounce((key, val) => {
window.localStorage.setItem(key, val);
window.dispatchEvent(new Event('storage'));
}, 500);
const defaultHttp = axios.create({
xsrfCookieName: 'csrftoken',
@ -15,8 +21,7 @@ defaultHttp.interceptors.response.use(response => {
const timeout = response?.headers['session-timeout'];
if (timeout) {
const timeoutDate = new Date().getTime() + timeout * 1000;
window.localStorage.setItem(SESSION_TIMEOUT_KEY, String(timeoutDate));
window.dispatchEvent(new Event('storage'));
updateStorage(SESSION_TIMEOUT_KEY, String(timeoutDate));
}
return response;
});

View File

@ -0,0 +1,19 @@
/**
* The debounce utility creates a debounced version of the provided
* function. The debounced function delays invocation until after
* the given time interval (milliseconds) has elapsed since the last
* time the function was called. This means that if you call the
* debounced function repeatedly, it will only run once after it
* stops being called.
*/
const debounce = (func, interval) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func(...args);
}, interval);
};
};
export default debounce;

View File

@ -0,0 +1,40 @@
import debounce from './debounce';
jest.useFakeTimers();
describe('debounce', () => {
test('it debounces', () => {
let count = 0;
const func = increment => {
count += increment;
};
const debounced = debounce(func, 1000);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
expect(count).toEqual(0);
jest.advanceTimersByTime(1000);
expect(count).toEqual(2);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
jest.advanceTimersByTime(1000);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
jest.advanceTimersByTime(1000);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
debounced(2);
jest.advanceTimersByTime(1000);
expect(count).toEqual(8);
});
});