I have 2 apps running in parallel:
- ReactJS front end app.
- Socket.IO and Kafka Streams embedded Java server.
The Java server will stream the data from brokers and its Socket.IO component will broadcast data to its clients. Clients receive the incoming data by
socketInstance.on('sv_broadcast_data', (data) => {
// State update method here
}
Note: Front end app is running 'socket.io-client' v2.5.0.
At the 'State update method here' comment, initially I used setState([...currentState, newData])
but whenever the Java server broadcasted a new event message, it did not append itself to the state array. Rather, it changed the first state, so the first state was gone and became the second new state. At first, I thought it was just because of a typo. Therefore, I tested it with console.log(newData)
.
Surprisingly, the console still logged all of the incoming data. Just the array state update method did not append new data and only replaced the first state with new data. I even logged the length of the state array and tested with bunch of messages from the Java server. The result was just a consistent length = 1
.
In the end, I tried an alternative state array update method
const updateState = (newData) => {
setEventLog(prevData => prevData.concat(newData)
}
And it worked! The new data got appended into the state array and the length is now > 1. I got so confused about this but I was happy that the solution worked. So, my question is what are the differences between the 2 state array update methods?
The FAIL one:
setState([...currentState, newData])
The SUCCESS one:
const updateState = (newData) => {
setEventLog(prevData => prevData.concat(newData)
}