use-pusher icon indicating copy to clipboard operation
use-pusher copied to clipboard

useChannel(false) to prevent eager channel connection

Open iamthesiz opened this issue 4 years ago • 4 comments

Sometimes you don't want to subscribe to a channel until another bit of data is available. It would be nice if you allowed useChannel to accept undefined, null, or false as a conditional to wait to subscribe. Similar to how useSWR does it. For instance:

const Messenger = () => {
  const my = useMe()
  const channelURL = my.username && `/api/messages/${my.username}`
  const channel = useChannel(channelURL)
  useEvent(channel, eventType, data => {
  })
}

In the above example, this prevents sending a subscription request from happening until we get my.username. Otherwise we would be subscribing to channel /api/messages/undefined

iamthesiz avatar Feb 16 '21 21:02 iamthesiz

Actually, this works, but it would be nice to not have the warning. I know it helps people if they haven't added a channel, but sometimes you don't want to add a channel.

iamthesiz avatar Feb 16 '21 23:02 iamthesiz

All good - I love it. Keen to add it in. Did you want to try a PR? Otherwise I can get to it later in the week.

mayteio avatar Feb 17 '21 01:02 mayteio

We’ve got two options - anything that evaluates to false doesn’t attempt to subscribe OR explicitly pass null to prevent subscription. This might be safer so that it still warns about passing undefined if people are generating channel names with an expression - similar to SWR as you mentioned.

mayteio avatar Feb 17 '21 01:02 mayteio

I personally like the false better. Then you don't have to do const url = bool ? 'url' : null you can just do const url = bool && 'url'. Cleaner in my opinion.

iamthesiz avatar Feb 18 '21 03:02 iamthesiz