-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (51 loc) · 1.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict'
const { useCallback, useEffect, useRef, useState } = require('react')
const { runSaga, stdChannel, identity } = require('little-saga')
module.exports = function useSaga({
saga,
args = [],
reducer = identity,
initialState,
initialAction,
customEnv,
taskContext,
}) {
const chanRef = useRef(null)
if (initialAction) {
initialState = reducer(initialState, initialAction)
}
const stateRef = useRef(initialState)
const [state, _setState] = useState(initialState)
useEffect(() => {
const getState = () => stateRef.current
const setState = nextState => {
stateRef.current = nextState
_setState(nextState)
}
const enhancer = put => action => {
// hit reducer before put the action into the channel
setState(reducer(getState(), action))
return put(action)
}
const channel = stdChannel().enhancePut(enhancer)
chanRef.current = channel
const rootTask = runSaga(
{
channel,
getState,
setState,
customEnv,
taskContext,
},
saga,
...args,
)
return () => {
rootTask.cancel()
chanRef.current.close()
chanRef.current = null
}
}, [])
const dispatch = action => chanRef.current.put(action)
return [state, useCallback(dispatch, [])]
}