I'm trying to read a JSON array from a file, store it as a List
in my component, and use it to display some stuff, yet I'm getting this error: Warning: Can't call setState on a component that is not yet mounted.
Here is my code:
The classes to display the list:
data class Member(val name: String, val githubUrl: String, val positions: List<String>)
external interface MemberListProps : RProps {
var members: List<Member>
}
class MemberList : RComponent<MemberListProps, RState>() {
override fun RBuilder.render() {
ul {
for (member in props.members) {
li {
styledA {
css { attrs.href = member.githubUrl }
+member.name
}
ul {
member.positions.forEach {
li { +it }
}
}
}
}
}
}
}
The use of the code:
external interface AppState : RState {
var members: List<Member>
}
class App : RComponent<RProps, AppState>() {
override fun RBuilder.render() {
state.members.forEach { _ ->
memberList {
members = state.members
}
}
}
private fun fetchMembers() = window.fetch("./members.json").unsafeCast<Array<Member>>()
override fun AppState.init() {
val jsonMembers = fetchMembers()
members = listOf()
setState {
members = jsonMembers.toList()
}
}
}
Thanks in advance!
Do not call
setState {}
inAppState.init()
I would suggest to move your code tocomponentDidMount()