Thanks in advance for any suggestions here. I am implementing websocket in ReactJS here and my goal is populating my history state with upcoming 'onmessage' events. Oddly to me, setHistory is emptying my array after receiving messages from 'websocket.onmessage' events. It even removes my initial state. Simplified version below:
function NotificationWebSocket ({object_id}) {
const [history, setHistory] = useState([{text: "The first notification"}]) //
function connectToWebSocket() {
const wsStart = (window.location.protocol === "https:" ? "wss://" : "ws://")
const url = 'localhost:8000/live/'
let socket = new ReconnectingWebSocket(wsStart + url + object_id)
socket.onmessage = e => {
console.log(e.data) // logs the received data correctly
setHistory([...history, {text: e.data}]) // ?? this is setting my history state array to null... ??
setHistory(history.append({text: e.data})) //also cleans my history array here.
}
}
useEffect(() => {
connectToWebSocket()
},[]) // so that we only connect to the websocket once
return (
<div>
We are on a live connection to the server.
{history.map(item=> <div>{item.text}</div>)}
</div>
)
}
Things to note here: I am using ReconnectingWebSocket library, although I tried not using it and the same thing occurs. My connectToWebSocket is being triggered from inside a useEffect cause otherwise I get a couple of websockets requests in the server.
Thanks again, Felipe.