ARTICLE AD BOX
Here is my on message handler:
const onMessage = (event: MessageEvent) => { try { const message = JSON.parse(event.data); const normalizedMsg = Array.isArray(message) ? message : [message]; bufferRef.current = [...bufferRef.current, ...normalizedMsg]; if (timeoutRef.current) clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { const flushed = [...bufferRef.current]; setFixtures(prev => [...prev, ...flushed]); bufferRef.current = []; }, DEBOUNCE_MS); } catch (error) { console.error('Error parsing message', error); } };Notice in here:
const flushed = [...bufferRef.current]; setFixtures(prev => [...prev, ...flushed]); bufferRef.current = [];I have to spread the bufferRef.current as without that none of my messages appear in the UI and the fixtures (via setFixtures) stays === [] In my previous code the array stayed empty which was this:
setFixtures(prev => [...prev, ...bufferRef.current]); bufferRef.current = [];Can you explain whether its one of these or something else:
React state updates are synchronous to schedule, but asynchronous to apply
A stale closure in the setTimeout
explanation based on interactions BETWEEN set timeouts
