Hello I seem to have a problem understanding the s...
# react
d
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
Looks like you use “old”
Listen
d
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
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
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
Copy code
val mycachedlambda = {
  setData { oldData ->
     calculateNewData(oldData)
  }
}
It's second setter signature, which provide previous state
d
Great, that worked! Thank you very much, I probably wouldn't have figured it out!
t