Skip to content

createEventHook

Category
Export Size
238 B
Last Changed
last week

Utility for creating event hooks

Usage

Creating a function that uses createEventHook

ts
import { createEventHook } from '@vueuse/core'

export function useMyFetch(url) {
  const fetchResult = createEventHook<Response>()
  const fetchError = createEventHook<any>()

  fetch(url)
    .then(result => fetchResult.trigger(result))
    .catch(error => fetchError.trigger(error.message))

  return {
    onResult: fetchResult.on,
    onError: fetchError.on,
  }
}
js
import { createEventHook } from '@vueuse/core'
export function useMyFetch(url) {
  const fetchResult = createEventHook()
  const fetchError = createEventHook()
  fetch(url)
    .then((result) => fetchResult.trigger(result))
    .catch((error) => fetchError.trigger(error.message))
  return {
    onResult: fetchResult.on,
    onError: fetchError.on,
  }
}

Using a function that uses createEventHook

vue
<script setup lang="ts">
import { useMyFetch } from './my-fetch-function'

const { onResult, onError } = useMyFetch('my api url')

onResult((result) => {
  console.log(result)
})

onError((error) => {
  console.error(error)
})
</script>

Type Declarations

typescript
/**
 * The source code for this function was inspired by vue-apollo's `useEventHook` util
 * https://github.com/vuejs/vue-apollo/blob/v4/packages/vue-apollo-composable/src/util/useEventHook.ts
 */
type Callback<T> =
  IsAny<T> extends true
    ? (...param: any) => void
    : [T] extends [void]
      ? (...param: unknown[]) => void
      : (...param: [T, ...unknown[]]) => void
export type EventHookOn<T = any> = (fn: Callback<T>) => {
  off: () => void
}
export type EventHookOff<T = any> = (fn: Callback<T>) => void
export type EventHookTrigger<T = any> = (
  ...param: IsAny<T> extends true ? unknown[] : [T, ...unknown[]]
) => Promise<unknown[]>
export interface EventHook<T = any> {
  on: EventHookOn<T>
  off: EventHookOff<T>
  trigger: EventHookTrigger<T>
  clear: () => void
}
/**
 * Utility for creating event hooks
 *
 * @see https://vueuse.org/createEventHook
 */
export declare function createEventHook<T = any>(): EventHook<T>

Source

SourceDocs

Contributors

Anthony Fu
wheat
OrbisK
IlyaL
Chris
Raman Paulau
Doctorwu
Curt Grimes
Guillaume Chau
丶远方
Amirreza Zarkesh
超杰
sun0day

Changelog

v12.1.0 on 12/22/2024
40265 - feat: add clear function (#4378)
v10.7.0 on 12/5/2023
3733b - fix: trigger should not ignore falsy values (#3561)
e48ca - fix: make createEventHook union type can be inferred correctly (#3569)
v10.6.0 on 11/9/2023
6040e - feat: allow trigger to optionally have no parameters (#3507)
v10.0.0-beta.0 on 3/14/2023
31347 - feat: allow awaiting on trigger (#2824)
dd514 - fix(useEventBus,createEventHook)!: dedupe registration of the same function (#2748)
v9.7.0 on 12/16/2022
fdd4d - feat(createEeventHook): auto dispose (#2518)

Released under the MIT License.