Skip to content

Commit e8e7ac2

Browse files
Use external API and coroutines to get real video information
1 parent f2f2a60 commit e8e7ac2

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

src/main/kotlin/App.kt

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
1+
import kotlinx.coroutines.async
12
import kotlinx.css.*
23
import react.*
34
import react.dom.*
45
import styled.css
56
import styled.styledDiv
7+
import kotlin.browser.window
8+
import kotlinx.coroutines.*
9+
10+
suspend fun fetchVideo(id: Int): Video {
11+
val response = window
12+
.fetch("https://my-json-server.typicode.com/kotlin-hands-on/kotlinconf-json/videos/$id")
13+
.await()
14+
.json()
15+
.await()
16+
return response as Video
17+
}
18+
19+
suspend fun fetchVideos(): List<Video> = coroutineScope {
20+
(1..25).map { id ->
21+
async {
22+
fetchVideo(id)
23+
}
24+
}.awaitAll()
25+
}
626

727
external interface AppState : RState {
828
var currentVideo: Video?
@@ -13,14 +33,16 @@ external interface AppState : RState {
1333
@JsExport
1434
class App : RComponent<RProps, AppState>() {
1535
override fun AppState.init() {
16-
unwatchedVideos = listOf(
17-
Video(1, "Building and breaking things", "John Doe", "https://youtu.be/PsaFVLr8t4E"),
18-
Video(2, "The development process", "Jane Smith", "https://youtu.be/PsaFVLr8t4E"),
19-
Video(3, "The Web 7.0", "Matt Miller", "https://youtu.be/PsaFVLr8t4E")
20-
)
21-
watchedVideos = listOf(
22-
Video(4, "Mouseless development", "Tom Jerry", "https://youtu.be/PsaFVLr8t4E")
23-
)
36+
unwatchedVideos = listOf()
37+
watchedVideos = listOf()
38+
39+
val mainScope = MainScope()
40+
mainScope.launch {
41+
val videos = fetchVideos()
42+
setState {
43+
unwatchedVideos = videos
44+
}
45+
}
2446
}
2547

2648
override fun RBuilder.render() {

0 commit comments

Comments
 (0)