react-use-websocket icon indicating copy to clipboard operation
react-use-websocket copied to clipboard

Feature: label-based sharing

Open csvan opened this issue 3 years ago • 1 comments

First of all, thanks for a fantastic lib!

Currently, passing the option shared: true allows multiple hook instances to share the same websocket. This is nice, but it would be even nicer if such sharing could be further granularised by using labels.

Example:

import useReactWebSocket from "react-use-websocket";

const url = 'https://mydomain.com';

// Unique socket
const first = useReactWebSocket(url, {shared: false})

// Single, global socket
const second = useReactWebSocket(url, {shared: true})
const third = useReactWebSocket(url, {shared: true})

// These share a socket if and only if the additional sharedLabel property matches. Note
// that this will mean that the first two will share a socket, but not the third
const fourth = useReactWebSocket(url, {shared: true, sharedLabel: 'foo'})
const fifth = useReactWebSocket(url, {shared: true, sharedLabel: 'foo'})
const sixth = useReactWebSocket(url, {shared: true, sharedLabel: 'bar'})

csvan avatar Oct 16 '22 16:10 csvan

Interesting! You can probably achieve this using query strings, though that might have upstream effects depending on how your server is set up.

robtaussig avatar Feb 10 '23 21:02 robtaussig