Skip to content

Commit 70a8d02

Browse files
Implement 'using external REST API'
1 parent e65b117 commit 70a8d02

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

src/main/kotlin/App.kt

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,36 @@ import react.dom.html.ReactHTML.div
1414
import react.dom.html.ReactHTML.p
1515
import react.dom.html.ReactHTML.img
1616

17+
suspend fun fetchVideo(id: Int): Video {
18+
val response = window
19+
.fetch("https://my-json-server.typicode.com/kotlin-hands-on/kotlinconf-json/videos/$id")
20+
.await()
21+
.text()
22+
.await()
23+
return Json.decodeFromString(response)
24+
}
25+
26+
suspend fun fetchVideos(): List<Video> = coroutineScope {
27+
(1..25).map { id ->
28+
async {
29+
fetchVideo(id)
30+
}
31+
}.awaitAll()
32+
}
33+
34+
val mainScope = MainScope()
35+
1736
val App = FC<Props> {
1837
var currentVideo: Video? by useState(null)
19-
var unwatchedVideos: List<Video> by useState(listOf(
20-
Video(1, "Opening Keynote", "Andrey Breslav", "https://youtu.be/PsaFVLr8t4E"),
21-
Video(2, "Dissecting the stdlib", "Huyen Tue Dao", "https://youtu.be/Fzt_9I733Yg"),
22-
Video(3, "Kotlin and Spring Boot", "Nicolas Frankel", "https://youtu.be/pSiZVAeReeg")
23-
))
24-
var watchedVideos: List<Video> by useState(listOf(
25-
Video(4, "Creating Internal DSLs in Kotlin", "Venkat Subramaniam", "https://youtu.be/JzTeAM8N1-o")
26-
))
38+
var unwatchedVideos: List<Video> by useState(emptyList())
39+
var watchedVideos: List<Video> by useState(emptyList())
40+
41+
useEffectOnce {
42+
mainScope.launch {
43+
unwatchedVideos = fetchVideos()
44+
}
45+
}
46+
2747
h1 {
2848
+"Hello, React+Kotlin/JS!"
2949
}

src/main/kotlin/Main.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import react.dom.html.ReactHTML.img
1212
import kotlinx.serialization.Serializable
1313
import react.dom.client.createRoot
1414

15+
@Serializable
1516
data class Video(
1617
val id: Int,
1718
val title: String,

0 commit comments

Comments
 (0)