Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useWebsocket): url to be ref/computed #2367

Merged
merged 5 commits into from Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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