pekim
pekim
SSolidJS
Created by pekim on 5/20/2024 in #support
Reactivity resulting from updates in a websocket event listener
I am struggling to understand why setting a signal in an event listener is not driving re-rendering for the signal. In the code below I observe reactivity for count2 (that is set in the setInterval callback), but not for count (that is set when a message is received on the websocket). I can see from the console.log in the message event handler that the values passed to setCount are changing. So my expectation is that the rendered value should change. I don't doubt that the reason for this is covered somewhere in the docs. I suspect that I'm simply misreading or misunderstanding something.
import { JSX, createEffect, createSignal } from 'solid-js';

interface Message {
count: number;
}

export default function SomeComponent(): JSX.Element {
const [count, setCount] = createSignal(0);
const [count2, setCount2] = createSignal(0);

createEffect(() => {
console.log('count', count());
console.log('count2', count2());
});

const ws = new WebSocket('ws://localhost:3000/_ws');
ws.addEventListener('message', (ev: MessageEvent) => {
const message: Message = ev.data;
console.log('message', message);
setCount(message.count);
});

setInterval(() => {
setCount2(count2() + 1);
}, 1000);

return (
<div>
<div>count : {count()}</div>
<div>count2 : {count2()}</div>
</div>
);
}
import { JSX, createEffect, createSignal } from 'solid-js';

interface Message {
count: number;
}

export default function SomeComponent(): JSX.Element {
const [count, setCount] = createSignal(0);
const [count2, setCount2] = createSignal(0);

createEffect(() => {
console.log('count', count());
console.log('count2', count2());
});

const ws = new WebSocket('ws://localhost:3000/_ws');
ws.addEventListener('message', (ev: MessageEvent) => {
const message: Message = ev.data;
console.log('message', message);
setCount(message.count);
});

setInterval(() => {
setCount2(count2() + 1);
}, 1000);

return (
<div>
<div>count : {count()}</div>
<div>count2 : {count2()}</div>
</div>
);
}
3 replies