https://kotlinlang.org logo
Title
d

Dirk

01/18/2023, 2:16 PM
Hello I seem to have a problem understanding the state hook. See the following screenshot: I have a state variable fachgutachterListen that is set after an API call under 1. The components is re-rendered with the new data. Data changes are transmitted from the server via websocket (3). When a changed data set is sent, the lambda for the data change in 2 is called. Now I have the problem that the state here is zero again as it was initially and does not have the current state, which is also displayed in the component. It is not clear to me where my error lies here, so that the current data can also be queried in 2, so that this can then be synchronised with the server change. Can anyone give me a hint as to where my error lies?
image.png
t

turansky

01/18/2023, 3:34 PM
Looks like you use “old”
Listen
d

Dirk

01/18/2023, 4:04 PM
You mean the value "listen", which is then transferred to the state in step 1? It contains the data records from the server and is also correctly transferred to the state. Only if an update comes via the websocket, then the state variable is null again under 2...
t

turansky

01/18/2023, 4:06 PM
then the state variable is null again under 2...
It’s expected, because you call effect once and use
…actualisieren
which was created at first render
d

Dirk

01/18/2023, 4:35 PM
So the lambda (val fgListenaktualisieren) is cached and not regenerated at all with the updated state if it changes due to the initial server call? I was assuming that React throws away and regenerates the component on state changes, keeping the state and only re-executing the effects on dependency changes. So how can I alternatively access the current state from the websocket session or the lambda?
t

turansky

01/18/2023, 5:59 PM
val mycachedlambda = {
  setData { oldData ->
     calculateNewData(oldData)
  }
}
It's second setter signature, which provide previous state
d

Dirk

01/19/2023, 1:11 PM
Great, that worked! Thank you very much, I probably wouldn't have figured it out!
t

turansky

01/19/2023, 2:45 PM