1
- import { useEffect , useState } from 'react'
2
- import { Observable , BehaviorSubject , Subject , noop } from 'rxjs'
1
+ import { useEffect , useState , useCallback } from 'react'
2
+ import { Observable , BehaviorSubject , Subject } from 'rxjs'
3
3
4
4
import { RestrictArray , VoidAsNull , Not } from './type'
5
5
6
- // https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
7
- type IfAny < T , Y , N > = 0 extends ( 1 & T ) ? Y : N
8
-
9
- type IsAny < T > = IfAny < T , true , false >
10
-
11
- type IsVoid < T > = IsAny < T > extends true ? false : [ T ] extends [ void ] ? true : false
12
-
13
- type VoidableCallback < EventValue > = IsVoid < EventValue > extends true ? ( ) => void : ( val : EventValue ) => void
14
-
15
6
export type EventCallbackState < EventValue , State , Inputs = void > = [
16
- VoidableCallback < EventValue > ,
7
+ ( e : EventValue ) => void ,
17
8
[ State extends void ? null : State , BehaviorSubject < State | null > , BehaviorSubject < RestrictArray < Inputs > | null > ]
18
9
]
19
10
export type ReturnedState < EventValue , State , Inputs > = [
@@ -53,9 +44,11 @@ export function useEventCallback<EventValue, State = void, Inputs = void>(
53
44
const inputSubject$ = new BehaviorSubject < RestrictArray < Inputs > | null > ( typeof inputs === 'undefined' ? null : inputs )
54
45
const stateSubject$ = new BehaviorSubject < State | null > ( initialValue )
55
46
const [ state , setState ] = useState ( initialValue )
56
- const [ returnedCallback , setEventCallback ] = useState < VoidableCallback < EventValue > > (
57
- ( ) => noop as VoidableCallback < EventValue > ,
58
- )
47
+ const [ event$ ] = useState ( new Subject < EventValue > ( ) )
48
+ function eventCallback ( e : EventValue ) {
49
+ return event$ . next ( e )
50
+ }
51
+ const returnedCallback = useCallback ( eventCallback , [ ] )
59
52
const [ state$ ] = useState ( stateSubject$ )
60
53
const [ inputs$ ] = useState ( inputSubject$ )
61
54
@@ -64,12 +57,7 @@ export function useEventCallback<EventValue, State = void, Inputs = void>(
64
57
} , inputs || [ ] )
65
58
66
59
useEffect ( ( ) => {
67
- const event$ = new Subject < EventValue > ( )
68
- function eventCallback ( e : EventValue ) {
69
- return event$ . next ( e )
70
- }
71
60
setState ( initialValue )
72
- setEventCallback ( ( ) => eventCallback as VoidableCallback < EventValue > )
73
61
let value$ : Observable < State >
74
62
75
63
if ( ! inputs ) {
0 commit comments