File size: 1,124 Bytes
48e00e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const searchForm = document.querySelector(".search-form");
const result = document.querySelector(".result");
const submitButton = document.querySelector(".submit-button");

const clearDiv = () => {
  result.innerHTML = "";
};

const buttonLoading = () => {
  submitButton.innerHTML = "loading...";
  submitButton.setAttribute("disabled", true);
};

const buttonDefault = () => {
  submitButton.innerHTML = "Submit";
  submitButton.removeAttribute("disabled");
};

const renderImg = (imageName) => {
  clearDiv();
  const img = document.createElement("img");
  img.src = `/images/${imageName}`;
  result.appendChild(img);
};

const getResult = async (searchQuery) => {
  const response = await fetch(`search?query=${searchQuery}`);
  const json = await response.json();

  return json.result;
};

searchForm.addEventListener("submit", async (event) => {
  event.preventDefault();

  const query = document.querySelector("#query");
  buttonLoading();
  try {
    const res = await getResult(query.value);
    renderImg(res);
  } catch (err) {
    console.error(err);
    clearDiv();
  } finally {
    buttonDefault();
  }
});