Hello I'm using react-kotlin but the `useState(0)`...
# javascript
f
Hello I'm using react-kotlin but the
useState(0)
Hook doesn't work! It throws the following Error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons (...)
and then lists the reasons. Why is that? My Code is the following:
Copy code
package <http://jsonApp.app|jsonApp.app>

import kotlinx.html.js.onClickFunction
import react.*
import react.dom.*

class App : RComponent<RProps, RState>() {
    override fun RBuilder.render() {
        div {
            +"jsonapp"
            counter()
        }
    }
}

fun RBuilder.jsonApp() = child(App::class) {}

fun RBuilder.counter() {
    div("count") {
        val countState: Pair<Int, (Int) -> Unit> = useState(0)

        span { +"You be walking a lot. ${countState.first} steps already" }
        button {
            attrs.onClickFunction = { countState.second(countState.first + 1) }
            +"Step"
        }
    }
}
Finally, I fixed it. Searched through kotlin-wrappers github issues and found this: https://github.com/JetBrains/kotlin-wrappers/issues/127 Apparently, RBuilder.fun() isn't a functional component, you have to define one like
fun counter() = functionalComponent<RProps>() {...}
and then call it with
child(counter())
👍 1
d
@Filippo Orru have you been able to access the
props
from within the
functionalComponent
I have been having the same issue as mentioned here https://github.com/JetBrains/kotlin-wrappers/issues/131 and was wondering if there is a work around
f
Sorry, I think my issues isn't quite the same as yours. I was trying to make a component without using a class and couldn't do it. Then I realized I needed to use
fun test = functionalComponent<>() = ...
instead of
RBuilder.test() = ...
directly. I didn't need to access the props so I didn't run into your problem.
d
@Filippo Orru I guess I could reword a little. To access the data, you are accessing the data from the store directly, instead of using the propagated props. Is that correct? If so have you encountered any issues doing that. I ask as the plain react examples that I have seen use the propagated props .
f
If you could send the js react example you're talking about as well your code, I might be able to help you. It's been a while since I encountered this problem and I stopped using kotlin and react shortly afterwards and started to learn Rust. Thus I'm a bit rusty, you could say ;)
d
@Filippo Orru thanks for the offer, but dont worry if you arent working in this stack anymore. Its really as described in the issue. Good luck with Rust
150 Views