I'm getting this error when trying to read a local JSON file in Kotlin/JS+React. What is going on?

214 Views Asked by At

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!

1

There are 1 best solutions below

0
On

Do not call setState {} in AppState.init() I would suggest to move your code to componentDidMount()

    override fun componentDidMount() {
        val jsonMembers = fetchMembers()
        members = listOf()

        setState {
            members = jsonMembers.toList()
        }
    }