I am learning to program and I want to do an asynchronous search. I got a code that works, but I do not understand why, I would like to know if anyone can help me to understand the code guide.
const list = document.getElementById("results");
const autoResults = (query) => {
fetch(`https://wagon-dictionary.herokuapp.com/autocomplete/${query}`)
.then(response => response.json())
.then((data) => {
data.words.forEach((result) => {
const resultLi = `<li>${result}</li>`;
list.insertAdjacentHTML("beforeend", resultLi);
});
});
};
const form = document.querySelector("#container input");
form.addEventListener("keyup", (event) => {
const inputText = event.currentTarget.value;
autoResults(inputText);
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div id="container">
<input type="text" id="search" placeholder="Search">
<ul id="results" >
</ul>
</div>
CodePudding user response:
Here is an improved version with comments
I use a debouncing method to not hammer the dictionary with a few letters
const list = document.getElementById("results");
const autoResults = (query) => {
fetch(`https://wagon-dictionary.herokuapp.com/autocomplete/${query}`) // call the site
.then(response => response.json()) // we get a JSON string back, parse it
.then((data) => { // here is a data object
list.innerHTML = data.words // here is an array of words
.map(word => `<li>${word}</li>`) // create a list using map
.join(''); // join to make a long string
});
};
const inputField = document.querySelector("#container input"); // it is a field, not a form
let tId, inputText; // make two global variables for timeout and text
inputField.addEventListener("input", (event) => { // input handles a paste too
const inputText = event.target.value;
// debounce
clearTimeout(tId); // stop any ongoing timeout
tId = setTimeout(() => autoResults(inputText), 300); // give the user 300 ms to type a letter
});
<div id="container">
<input type="text" id="search" placeholder="Search">
<ul id="results" >
</ul>
</div>