Although this is a getter the value returned by it...
# react
m
Although this is a getter the value returned by it seems to always be the initial value in the scope of the closure
Copy code
var chats by useState(listOf<String>("first"))

    useEffectOnce {
        GlobalScope.launch {
            client.rtmStream().collect {
                val current = chats // always initial value
                println(current)
                chats = current + it.message
            }
        }
    }
Am I doing something wrong?
d
useState
returns an array containing the value and a function to set the value, so the value is captured in that array and isn't actually a function to get the current value. The getter function allowing you to use
by
just accesses the first element in that array which is just the captured value:
Copy code
inline operator fun getValue(
        thisRef: Nothing?,
        property: KProperty<*>,
    ): T =
        asDynamic()[0]
m
So any way of getting the current value? Or do I have to keep a separate reference in the closure?
d
So you wouldn't have an updated value unless the effect depends on that state and reruns when it changes. If you only want the effect to run once I think you would have to use
useRef
instead https://stackoverflow.com/a/60643670
So in kotlin that would be something like this:
Copy code
var chats by useState(listOf<String>("first"))
val chatsRef = useRef(chats)
chatsRef.current = chats
Then in your callback you can access
chatsRef.current
to get the current value
1
👍 1
t
Also
cleanup
missed
m
Why is the cleanup required? Seems to me like no resources are leaking, not even in the example you gave me
Ohhh, the cleanup is required because the subscription might no longer be necessary if the component is removed from the tree. Right?
t
Yes
c
This way you don't have to think about suspension or cleanup every time in your code
1