react-hooks icon indicating copy to clipboard operation
react-hooks copied to clipboard

Do not subscribe if channel empty string

Open cmcaboy opened this issue 4 years ago • 2 comments

I was thinking of some way to conditionally subscribe, but the hook does not allow for that. As a work-around, I would like for the useChannel hook to subscribe only when the channel name is a truthy value.

cmcaboy avatar Dec 29 '21 03:12 cmcaboy

Would it be better to use an if condition around the call to useChannel? Otherwise we'd have to return something valid from the useChannel call that wouldn't make semantic sense.

thisisjofrank avatar May 12 '22 20:05 thisisjofrank

Would it be better to use an if condition around the call to useChannel

I don't think this is possible, you would break the rules of hooks.

My specific use-case is to lock usePresence for users behind a paywall. I wouldn't want to even spend connections with invalid users.

For now, I'm planning to write a component that conditionally render other components. Those would call useChannel/usePresence or stub them:

const App = () => (
  <MyChannelProvider>
     <Component />
  </MyChannelProvider>
)

const MyChannelProvider = () => {
  if(isValidUser) {
    return <ActualChannelProvider />
  } else {
    return <StubbedChannelProvider />
  }
}

const Component = () => {
  const channelData = useMyChannelProviderContext();
}

But it is a lot of boilerplate code. Having a way to skip the hook would be nice (similar to how we can conditionally fetch data with SWR, or skip Apollo requests).

michelts avatar Apr 27 '23 14:04 michelts