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

you can turn off automatic connection beforehand

Open xushnud123 opened this issue 2 years ago • 6 comments

i want to cancel automatic connection beforehand how can i do it

xushnud123 avatar Sep 08 '23 19:09 xushnud123

There's a third parameter to the useWebSocket hook which isn't documented.

Setting it to false will prevent automatic connection and disconnect the websocket if it is already connected

ElectricCoffee avatar Oct 11 '23 09:10 ElectricCoffee

This should've been documented. I've been using hours to find a workaround for this :D

HarunKilic avatar Oct 19 '23 10:10 HarunKilic

This should've been documented. I've been using hours to find a workaround for this :D

I only found out about it because I had a feature request to add it in: #208

ElectricCoffee avatar Oct 19 '23 10:10 ElectricCoffee

This should've been documented. I've been using hours to find a workaround for this :D

I’m sorry for your time! It is not entirely undocumented: https://github.com/robtaussig/react-use-websocket#interface

Do you have any thoughts regarding a better place for it?

robtaussig avatar Oct 19 '23 23:10 robtaussig

This should've been documented. I've been using hours to find a workaround for this :D

I’m sorry for your time! It is not entirely undocumented: https://github.com/robtaussig/react-use-websocket#interface

Do you have any thoughts regarding a better place for it?

I was looking for a section that would show how to disable it at initialization.

HarunKilic avatar Oct 21 '23 11:10 HarunKilic

I stumbled upon my solution to my react-native problem in this thread. I want the websocket to disconnect when the app is in the background and reconnect when the app is foregrounded. Some delay could be built into this too.

Here's how I solved it for my use case in react-native:

import { useAppState } from "@react-native-community/hooks"

// in your functional component:
const appState = useAppState()
const appIsActive = appState === "active"
const ws = useWebSocket(
  socketURL, 
  {
      shouldReconnect: () => appIsActive,
      // Other options
  },
  appIsActive, // boolean to indicate if the websocket should be connected or not.
)

markrickert avatar Aug 12 '24 18:08 markrickert