module author Surmon <https://github.com/surmon-china>
  import { useState as useReactState } from 'react' ; import { DebuggerOptions , ReactiveEffect , EffectScheduler } from '@vue/reactivity' ; import { onBeforeUnmount } from '../lifecycle' ; import { callWithErrorHandling , callWithAsyncErrorHandling } from '../logger' ; import { WATCH_CLEANUP_ERROR , WATCH_CALLBACK_ERROR } from './patch' ; export type WatchEffectOptions = DebuggerOptions ; export type WatchStopHandle = ( ) => void ; export type InvalidateCallbackRegistrator = ( callback : ( ) => void ) => void ; export type WatchEffect = ( onInvalidate : InvalidateCallbackRegistrator ) => any ; example export function watchEffect ( effect , options = { } ) { let effector ; let cleanup ; const onInvalidate = ( fn ) => { cleanup = effector . onStop = ( ) => { callWithErrorHandling ( fn , WATCH_CLEANUP_ERROR ) ; } ; } ; const scheduler = ( ) => { if ( ! effector . active ) { return ; } effector . run ( ) ; } ; const getter = ( ) => { cleanup ?. ( ) ; return callWithAsyncErrorHandling ( effect , WATCH_CALLBACK_ERROR , [ onInvalidate ] ) ; } ; effector = new ReactiveEffect ( getter , scheduler ) ; effector . onTrack = options . onTrack ; effector . onTrigger = options . onTrigger ; effector . run ( ) ; return ( ) => effector . stop ( ) ; } export function useWatchEffect ( effect , options ? ) { const [ stopHandle ] = useReactState ( ( ) => watchEffect ( effect , options ) ) ; onBeforeUnmount ( ( ) => stopHandle ?. ( ) ) ; return stopHandle ; }