robtaussig / react-use-websocket

React Hook for WebSocket communication
MIT License
1.55k stars 135 forks source link

you can turn off automatic connection beforehand #204

Open xushnud123 opened 1 year ago

xushnud123 commented 1 year ago

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

ElectricCoffee commented 11 months ago

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

HarunKilic commented 11 months ago

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

ElectricCoffee commented 11 months ago

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

robtaussig commented 11 months ago

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?

HarunKilic commented 11 months ago

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.

markrickert commented 1 month ago

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.
)