1+ import kotlinx.coroutines.async
12import kotlinx.css.*
23import react.*
34import react.dom.*
45import styled.css
56import 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
727external interface AppState : RState {
828 var currentVideo: Video ?
@@ -13,14 +33,16 @@ external interface AppState : RState {
1333@JsExport
1434class 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