Hello I am attempting to use WebSockets together with react and (electron if it matters)
On open behaves as I would expect. So the message 'Connection opened' gets added to the start of a new array and is displayed correctly. Basically an unshift.
OnMessage however behaves bizarrely. It just overwrites the first element of the array. Even though the same 'addMessage' function is being called.
The console log confirms this with the output being the array.
What could be causing this?
I tried placing the on message assignments into different useEffect hooks like in
this post but it apparently had no effect.
const DebugScreen: FunctionComponent = () => {
const [messages, setMessages] = useState<Array<string>>([]);
const socket = useRef<WebSocket>();
useEffect(() => {
openConnection();
return () => {
if (socket.current) {
socket.current.close();
}
}
}, []);
const openConnection = () => {
socket.current = new WebSocket('wss://localhost');
if (!socket.current) return;
socket.current.onopen = () => addMessage('Connection opened');
socket.current.onmessage = ({ data }) => addMessage(data.toString());
socket.current.onerror= err => console.log(err);
}
const addMessage = (message: string) => {
setMessages([message, ...messages]);
};
const sendWebsocketMessage = () {
if (!socket.current) return;
console.log('sendWebsocketMessage: ' + messages);
socket.current.send(
JSON.stringify({
test: 'data'
},
})
);
}
const logMessages = () => console.log(messages);
return (
<div>
{/* Display server responses */}
{messages.map((message) => <p key={Math.random().toString()}>{message}</p>)}
{/* 1) Connect to Cortex Socket */}
<button onClick={openConnection} >1) Open Cortex Connection</button>
{/* 2) Sent WebSocket message */}
<button onClick={sendWebsocketMessage}>Request Cortex Access</button>
<button onClick={logMessages}>Log Messages</button>
</div>
);
}
question from:
https://stackoverflow.com/questions/65941021/react-usestate-with-websocket-causes-array-to-not-update-correctly 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…