Skip to content

createEventHook

Category
Export Size
169 B
Last Changed
5 days ago

Utility for creating event hooks

Demo

Usage

Creating a function that uses createEventHook

tsx
import { 
createEventHook
} from '@reause/shared'
export function
useMyFetch
(
url
: string) {
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
,
} }

Using a function that uses createEventHook

tsx
import { 
useListener
} from '@reause/shared'
import {
useMyFetch
} from './my-fetch-function'
function
MyApp
() {
const {
onResult
,
onError
} =
useMyFetch
('/my-api-url')
useListener
(
onResult
, (
result
) => {
console
.
log
(
result
)
})
useListener
(
onError
, (
error
) => {
console
.
error
(
error
)
}) return <
div
>...</div>
}

Type Declarations

ts
export type EventHookOn<T = any> = (fn: Callback<T>) => () => void

export type EventHookOff<T = any> = (fn: Callback<T>) => void

export type EventHookTrigger<T = any> = (...param: Parameters<Callback<T>>) => Promise<unknown[]>

export interface EventHook<T = any> {
    on: EventHookOn<T>;
    off: EventHookOff<T>;
    trigger: EventHookTrigger<T>;
    clear: () => void;
}

export type EventHookReturn<T> = EventHook<T>

type Callback<T> = IsAny<T> extends true ? (...param: any) => void : ([
    T
] extends [
    void
] ? (...param: unknown[]) => void : [
    T
] extends [
    any[]
] ? (...param: T) => void : (...param: [
    T,
    ...unknown[]
]) => void)

export function createEventHook<T = any>(): EventHookReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.7 on
534c2 - refactor(shared)!: return the off function from listener registrars
v0.1.0 on
50ecc - fix(shared): resolve createEventHook audit findings (#698)
c0578 - fix(docs): resolve dead doc links and repair useMediaControls fence
62c92 - feat(shared): add createEventHook (#4)

Released under the MIT License. v0.1.8