Be more careful about caching the input query for autocomplete

This commit is contained in:
byte[] 2021-10-25 21:17:57 -04:00
parent fee0d030a8
commit d43ae04c1c

View file

@ -100,12 +100,12 @@ function createParent() {
document.body.appendChild(parent); document.body.appendChild(parent);
} }
function showAutocomplete(suggestions, targetInput) { function showAutocomplete(suggestions, fetchedTerm, targetInput) {
// Remove old autocomplete suggestions // Remove old autocomplete suggestions
removeParent(); removeParent();
// Save suggestions in cache // Save suggestions in cache
cache[targetInput.value] = suggestions; cache[fetchedTerm] = suggestions;
// If the input target is not empty, still visible, and suggestions were found // If the input target is not empty, still visible, and suggestions were found
if (targetInput.value && targetInput.style.display !== 'none' && suggestions.length) { if (targetInput.value && targetInput.style.display !== 'none' && suggestions.length) {
@ -115,8 +115,8 @@ function showAutocomplete(suggestions, targetInput) {
} }
} }
function getSuggestions() { function getSuggestions(term) {
return fetch(inputField.dataset.acSource + inputField.value).then(response => response.json()); return fetch(`${inputField.dataset.acSource}${term}`).then(response => response.json());
} }
function listenAutocomplete() { function listenAutocomplete() {
@ -130,18 +130,18 @@ function listenAutocomplete() {
timeout = window.setTimeout(() => { timeout = window.setTimeout(() => {
inputField = event.target; inputField = event.target;
originalTerm = inputField.value; originalTerm = inputField.value;
const fetchedTerm = inputField.value;
const {ac, acMinLength} = inputField.dataset; const {ac, acMinLength} = inputField.dataset;
if (ac && (inputField.value.length >= acMinLength)) { if (ac && (fetchedTerm.length >= acMinLength)) {
if (cache[fetchedTerm]) {
if (cache[inputField.value]) { showAutocomplete(cache[fetchedTerm], event.target);
showAutocomplete(cache[inputField.value], event.target);
} }
else { else {
// inputField could get overwritten while the suggestions are being fetched - use event.target // inputField could get overwritten while the suggestions are being fetched - use event.target
getSuggestions().then(suggestions => showAutocomplete(suggestions, event.target)); getSuggestions(fetchedTerm).then(suggestions => showAutocomplete(suggestions, fetchedTerm, event.target));
} }
} }
}, 300); }, 300);
}); });