Skip to content

Commit

Permalink
feat(useWebsocket): url to be ref/computed (#2367)
Browse files Browse the repository at this point in the history
  • Loading branch information
rotu committed Nov 8, 2022
1 parent f78c49a commit 86013c4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
2 changes: 2 additions & 0 deletions packages/core/useWebSocket/index.md
Expand Up @@ -22,6 +22,8 @@ Auto-connect (enabled by default).

This will call `open()` automatically for you and you don't need to call it by yourself.

If url is provided as a ref, this also controls whether a connection is re-established when its value is changed (or whether you need to call open() again for the change to take effect).

### Auto-close

Auto-close-connection (enabled by default).
Expand Down
17 changes: 9 additions & 8 deletions packages/core/useWebSocket/index.ts
@@ -1,7 +1,7 @@
import type { Ref } from 'vue-demi'
import { ref } from 'vue-demi'
import type { Fn } from '@vueuse/shared'
import { tryOnScopeDispose, useIntervalFn } from '@vueuse/shared'
import { ref, watch } from 'vue-demi'
import type { Fn, MaybeComputedRef } from '@vueuse/shared'
import { resolveRef, tryOnScopeDispose, useIntervalFn } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'

export type WebSocketStatus = 'OPEN' | 'CONNECTING' | 'CLOSED'
Expand Down Expand Up @@ -143,7 +143,7 @@ function resolveNestedOptions<T>(options: T | true): T {
* @param url
*/
export function useWebSocket<Data = any>(
url: string,
url: MaybeComputedRef<string | URL>,
options: UseWebSocketOptions = {},
): UseWebSocketReturn<Data> {
const {
Expand All @@ -159,6 +159,7 @@ export function useWebSocket<Data = any>(
const data: Ref<Data | null> = ref(null)
const status = ref<WebSocketStatus>('CLOSED')
const wsRef = ref<WebSocket | undefined>()
const urlRef = resolveRef(url)

let heartbeatPause: Fn | undefined
let heartbeatResume: Fn | undefined
Expand Down Expand Up @@ -206,7 +207,7 @@ export function useWebSocket<Data = any>(
if (explicitlyClosed)
return

const ws = new WebSocket(url, protocols)
const ws = new WebSocket(urlRef.value, protocols)
wsRef.value = ws
status.value = 'CONNECTING'

Expand Down Expand Up @@ -281,9 +282,6 @@ export function useWebSocket<Data = any>(
heartbeatResume = resume
}

if (immediate)
_init()

if (autoClose) {
useEventListener(window, 'beforeunload', () => close())
tryOnScopeDispose(close)
Expand All @@ -296,6 +294,9 @@ export function useWebSocket<Data = any>(
_init()
}

if (immediate)
watch(urlRef, open, { immediate: true })

return {
data,
status,
Expand Down

0 comments on commit 86013c4

Please sign in to comment.