Trying to show a list of values which are received...
# react
s
Trying to show a list of values which are received by rsocket client, but its not working at all.
Copy code
val App = FC<Props> {
        val (responses, setResponses) = useState<List<String>>(emptyList())

        useEffectOnce {
            scope.launch {
                stream.collect { payload ->
                    val response = payload.data.readText()
                    println("Prev: $responses, Got $response")
                    setResponses(responses + response)
                }
            }
        }

        div {
            div {
                +"Total number of response = ${responses.size}"
            }

            for (response in responses) {
                div {
                    key = response
                    +response
                }
            }
        }
    }
Shows -
Copy code
Total number of response = 1
423
The total number stays at 1 and the second lines updates 1 to 2 to 3 etc
1
t
Copy code
setResponses { prev -> prev + response }
? cc @Sergei Grishchenko
s
that worked but i don't understand why
t
Because state in react is asynchronous
s
I see. How can make it work if I have
Copy code
var responses by useState<List<String>>(emptyList())
I tried
Copy code
responses = responses + response
but it didn't work 😕
t
That is why we have destructuring for setter and getter
If your new state depends on previous - you can use destructuring with extended setter (your case)
Base:
Copy code
// for complex cases
val (count, setCount) = useState(0)
Short - with Kotlin sugar:
Copy code
// for simple cases
var count by useState(0)
s
Aha. I see. So in
useEffect
, the value of
responses
is always the
emptyList()
, in other words, it doesn't see the updated values?
t
Yes, it’s like async state works
s
Got it. Thanks a lot for the help!
👍 1