/
App.kt
93 lines (79 loc) · 2.12 KB
/
App.kt
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
92
93
package app
import common.alert
import common.loading
import common.searchBar
import giphy.*
import kotlinx.coroutines.experimental.async
import lodash.lodash
import react.*
import react.dom.div
import react.dom.h1
interface AppState : RState {
var giphies: Array<Giphy>
var selectedGiphy: Giphy
var errorMessage: String
var loading: Boolean
}
class App : RComponent<RProps, AppState>() {
override fun AppState.init() {
giphies = emptyArray()
selectedGiphy = DummyGiphy
errorMessage = ""
loading = false
}
override fun RBuilder.render() {
div("container") {
h1("text-center") {
+"Giphy Search"
}
searchBar(onSearchTermChange = lodash.debounce(::startSearchCoroutines, 300))
alert(state.errorMessage)
loading(state.loading)
giphyDetails(state.selectedGiphy)
giphyList(state.giphies, ::selectGiphy)
}
}
fun selectGiphy(giphy: Giphy) {
setState {
selectedGiphy = giphy
}
}
fun startSearch(term: String) {
setState {
loading = true
errorMessage = ""
}
giphySearch(term).then { result: Array<Giphy> ->
setState {
selectedGiphy = result[0]
giphies = result
loading = false
}
}.catch { throwable: Throwable ->
setState {
errorMessage = throwable.toString()
loading = false
}
}
}
fun startSearchCoroutines(term: String) = async {
setState {
loading = true
errorMessage = ""
}
try {
val result: Array<Giphy> = giphySearchCoroutines(term)
setState {
selectedGiphy = result[0]
giphies = result
loading = false
}
} catch (t: Throwable) {
setState {
errorMessage = t.toString()
loading = false
}
}
}
}
fun RBuilder.app() = child(App::class) {}