-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
91 lines (77 loc) · 2.37 KB
/
app.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { debounce } from 'lodash-es'
import { fromEvent } from 'rxjs'
import { ajax } from 'rxjs/ajax'
import {
debounceTime,
map,
switchMap,
distinctUntilChanged,
tap,
} from 'rxjs/operators'
import Meal from './meal'
const apiEndPoint = 'https://www.themealdb.com/api/json/v1/1/search.php'
const searchInput = document.querySelector('.searchInput')
const recipeList = document.querySelector('.recipeList')
let previousInputValue = ''
// Using Vanilla JS
const debouncedInputHandler = debounce(async ({ target: { value: inputValue } }) => {
if (!inputValue) {
return
}
if (previousInputValue === inputValue) {
return
}
recipeList.innerHTML = '<h3>Loading...</h3>'
// fetch(`${apiEndPoint}?f=${inputValue}`, {
// method: 'GET',
// })
// .then((response) => response.json())
// .then(({ meals }) => {
// recipeList.innerHTML = meals
// .map((meal) => new Meal(meal))
// .map((mealInstance) => mealInstance.renderToString())
// .join('')
// })
// .catch(() => {
// recipeList.innerHTML = '<h3>An error has occurred when fetching data...</h3>'
// })
try {
const response = await fetch(`${apiEndPoint}?f=${inputValue}`, {
method: 'GET',
})
const { meals } = await response.json()
recipeList.innerHTML = meals
.map((meal) => new Meal(meal))
.map((mealInstance) => mealInstance.renderToString())
.join('')
} catch {
recipeList.innerHTML = '<h3>An error has occurred when fetching data...</h3>'
}
previousInputValue = inputValue
}, 1000)
searchInput.addEventListener('input', debouncedInputHandler)
// Using RxJS
// const inputStream = fromEvent(searchInput, 'input')
// .pipe(
// map((event) => event.target.value),
// debounceTime(1000),
// distinctUntilChanged(),
// tap(() => recipeList.innerHTML = '<h3>Loading...</h3>'),
// switchMap((inputValue) =>
// ajax(`${apiEndPoint}?f=${inputValue}`, { method: 'GET' })
// .pipe(
// map(({ response }) => response ? response.meals : []),
// ),
// ),
// )
// inputStream.subscribe({
// next: (meals) => {
// recipeList.innerHTML = meals
// .map((meal) => new Meal(meal))
// .map((mealInstance) => mealInstance.renderToString())
// .join('')
// },
// error: () => {
// recipeList.innerHTML = '<h3>An error has occurred when fetching data...</h3>'
// },
// })