Skip to content

Commit

Permalink
fix(useWebWorker): SSR compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Mar 14, 2021
1 parent bfb4083 commit 1a31fcc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
6 changes: 3 additions & 3 deletions packages/core/useFetch/index.md
Expand Up @@ -128,7 +128,7 @@ interface UseFetchReturnBase<T> {
*/
response: Ref<Response | null>
/**
* Any fetch errors that may have occured
* Any fetch errors that may have occurred
*/
error: Ref<any>
/**
Expand Down Expand Up @@ -179,11 +179,11 @@ export interface BeforeFetchContext {
*/
url: string
/**
* The requset options of the current request
* The request options of the current request
*/
options: RequestInit
/**
* Cancels the current requset
* Cancels the current request
*/
cancel: Fn
}
Expand Down
4 changes: 3 additions & 1 deletion packages/core/useWebWorker/index.md
Expand Up @@ -39,11 +39,13 @@ const { data, post, terminate } = useWebWorker('/path/to/worker.js')
*
* @see {@link https://vueuse.org/useWebWorker}
* @param url
* @param workerOptions
* @param options
*/
export declare function useWebWorker(
url: string,
options?: WorkerOptions
workerOptions?: WorkerOptions,
options?: ConfigurableWindow
): {
data: Ref<any>
post: {
Expand Down
29 changes: 21 additions & 8 deletions packages/core/useWebWorker/index.ts
Expand Up @@ -2,15 +2,25 @@

import { ref, Ref } from 'vue-demi'
import { tryOnUnmounted } from '@vueuse/shared'
import { ConfigurableWindow, defaultWindow } from '../_configurable'

/**
* Simple Web Workers registration and communication.
*
* @see {@link https://vueuse.org/useWebWorker}
* @param url
* @param workerOptions
* @param options
*/
export function useWebWorker(url: string, options?: WorkerOptions) {
export function useWebWorker(
url: string,
workerOptions?: WorkerOptions,
options: ConfigurableWindow = {},
) {
const {
window = defaultWindow,
} = options

const data: Ref<any> = ref(null)
let worker: Worker

Expand All @@ -28,15 +38,18 @@ export function useWebWorker(url: string, options?: WorkerOptions) {
worker.terminate()
}

worker = new Worker(url, options)
if (window) {
// @ts-expect-error untyped
worker = new window.Worker(url, workerOptions)

worker.onmessage = (e: MessageEvent) => {
data.value = e.data
}
worker.onmessage = (e: MessageEvent) => {
data.value = e.data
}

tryOnUnmounted(() => {
worker.terminate()
})
tryOnUnmounted(() => {
worker.terminate()
})
}

return {
data,
Expand Down

0 comments on commit 1a31fcc

Please sign in to comment.