frontend: implement fetchwithBackoff

We're fetching too soon and too often stuff from the backend. Making
the search input behaviour a bit flaky.

Implementing a backoff fetching strategy. We'll trigger the query only
after 500ms of inactivity and will cancel the previous requests before
triggering a new one.
This commit is contained in:
Félix Baylac-Jacqué 2022-02-12 23:32:32 +01:00
parent 3fe2a4af9c
commit c9a0a898aa

View file

@ -167,7 +167,7 @@
} }
// Function to update list of voies (calls backend API) // Function to update list of voies (calls backend API)
function updateVoies(codeInsee, search = '') { function updateVoies(search = '') {
var api = "addresses/fantoirvoies/" + codeInsee + '?limit=15'; var api = "addresses/fantoirvoies/" + codeInsee + '?limit=15';
if (search != '') { if (search != '') {
api += "&s=" + search; api += "&s=" + search;
@ -201,6 +201,21 @@
console.error("Error fetching communes:", err) console.error("Error fetching communes:", err)
}) })
} }
function fetchWithBackoff (fetchFn, timeout, input) {
if(timeout !== null) {
clearTimeout(timeout);
}
if (input.length < 3) {
return null;
}
timeout = setTimeout(() => {
const cleanInput = sanitizeInputStr(input);
fetchFn(cleanInput);
}, 100);
return timeout;
}
$('#methodAddress').on('show.bs.collapse', function () { $('#methodAddress').on('show.bs.collapse', function () {
$('#communeInput').trigger('input') $('#communeInput').trigger('input')
$('#communeInput').trigger('keyup') $('#communeInput').trigger('keyup')
@ -216,10 +231,10 @@
$('#numeroVoieInput').focus(); $('#numeroVoieInput').focus();
}); });
$('#communeInput').on('keyup', function () { let timeoutCommune = null;
$('#communeInput').on('input', function () {
controllerCommunes.abort(); controllerCommunes.abort();
inputStr = sanitizeInputStr($(this).val()); timeoutCommune = fetchWithBackoff(updateCommunes, timeoutCommune, $(this).val());
updateCommunes(inputStr);
}); });
$('#communeInput').on('input', function () { $('#communeInput').on('input', function () {
@ -227,10 +242,11 @@
$('#voieForm').collapse('hide'); $('#voieForm').collapse('hide');
} }
}); });
$('#voieInput').on('keyup', function () {
let timeoutVoie = null;
$('#voieInput').on('input', function () {
controllerVoies.abort(); controllerVoies.abort();
inputStr = sanitizeInputStr($(this).val()); timeoutVoie = fetchWithBackoff(updateVoies, timeoutVoie, $(this).val());
updateVoies(codeInsee, inputStr);
}); });
$('#voieInput').on('input', function () { $('#voieInput').on('input', function () {
if ($(this).val() === '') { if ($(this).val() === '') {