sergiodxa / remix-utils

A set of utility functions and types to use with Remix.run
https://sergiodxa.github.io/remix-utils/
MIT License
2.1k stars 117 forks source link

Add onEvent callback to useEventSource #341

Open KubaJastrz opened 6 months ago

KubaJastrz commented 6 months ago

Adds a callback to event source stream, which fires whenever new data comes in. Useful if you don't want to merely display the latest message value, but rather do something with it. Like displaying a toast, computing a new state, analytics, you name it.

Usage:

useEventSource("/sse", {
    onEvent(data) {
        console.log(data);
    },
});
sergiodxa commented 6 months ago

This can easily be done with an effect in user-land:

let value = useEventSource("/sse");
useEffect(() => {
  // do something with `value`
}, [value])
KubaJastrz commented 6 months ago

That's only if the value has changed. I suppose it could be worked around by adding some unique identifier inside of the message.

KubaJastrz commented 4 months ago

@sergiodxa are you interested in adding this change?

bitofbreeze commented 2 months ago

@KubaJastrz @sergiodxa Could we extend useEventSource to allow reconnecting when the stream is closed? I don't see any way of currently doing this, and I think using a similar idea as here but making onEvent report disconnects too or adding perhaps an onError handler could make this possible.

For reference, here are the handlers partykit's websocket client hook exposes:

image