Javascript 30 - Gün 6

Bugünün projesi fetch kullanarak veri çekmeyi ve bu veri üzerinde filtreleme işlemleri yapmayı içeriyor.

Projenin demosu : Demo

Başlangıç dosyalarını bulabileceğiniz repom: js-30 | github

Çok karmaşık bir proje olmadığından sadece kodu paylaşıyorum:

 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4  <meta charset="UTF-8" />
 5  <title>Type Ahead 👀</title>
 6  <link rel="stylesheet" href="style.css" />
 7  <link rel="icon" href="https://fav.farm/🔥" />
 8</head>
 9
10<body>
11  <form class="search-form">
12    <input type="text" class="search" placeholder="Şehir veya Eyalet" />
13    <ul class="suggestions">
14      <li>Şehir/eyalete göre filtrele</li>
15    </ul>
16  </form>
17<script>
18// Verinin bulunduğu url'yi saklar
19const endpoint = "https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json";
20
21// Şehir ve eyaletleri saklamak için bir dizi oluşturur
22const cities = [];
23
24// Fetch API kullanarak veriyi alır ve spread operatörü yardımıyla diziyi günceller.
25fetch(endpoint)
26  .then((res) => res.json())
27  .then((data) => {
28    cities.push(...data);
29  });
30
31// Dizideki kelimeleri arar 
32function findMatches(word, cities) {
33  return cities.filter((place) => {
34    // Aranan kelimenin şehir/eyalet ile eşleşip eşleşmediğini kontrol eder
35    const regex = new RegExp(word, "gi");
36    return place.city.match(regex) || place.state.match(regex);
37  });
38}
39
40// Bulunan sonuçları DOM'da görüntüler 
41function renderMatches() {
42  const matchArray = findMatches(this.value, cities);
43  // Eşleşen kelimeleri sarı bir arka plana sahip 'hl' sınıfına sahip bir span içinde gösterir.
44  const html = matchArray
45    .map((place) => {
46      const regex = new RegExp(this.value, "gi");
47      const cityName = place.city.replace(
48        regex,
49        `<span class="hl">${this.value}</span>`
50      );
51      const stateName = place.state.replace(
52        regex,
53        `<span class="hl">${this.value}</span>`
54      );
55
56      // Intl API sayıların formatlanmasını sağlar. (Örneğin 8405837-> 8,405,837 )
57      return `<li> 
58          <span class="name">${cityName}, ${stateName} </span>
59          <span class="population">${new Intl.NumberFormat().format(
60            place.population
61          )}</span>
62      </li>`;
63    })
64    .join("");
65  resultsContainer.innerHTML = html;
66  console.log(matchArray);
67}
68
69// HTML'deki gerekli öğeleri seçer
70const filterInput = document.querySelector(".search");
71const resultsContainer = document.querySelector(".suggestions");
72
73// Olay dinleyicilerini ekler
74filterInput.addEventListener("change", renderMatches);
75filterInput.addEventListener("keyup", renderMatches);
76</script>
77</body>
78</html>

Bu projeden öğrendiklerim

  • Intl api ile tarih, saat ve para birimleri formatlanabilir.