-
-
Notifications
You must be signed in to change notification settings - Fork 567
/
useReducerAtom.ts
38 lines (34 loc) 路 1.03 KB
/
useReducerAtom.ts
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
import { useCallback } from 'react'
import { useAtom } from 'jotai'
import type { PrimitiveAtom } from 'jotai'
import type { Scope } from '../core/atom'
/* this doesn't seem to work as expected in TS4.1
export function useReducerAtom<Value, Action>(
anAtom: PrimitiveAtom<Value>,
reducer: (v: Value) => Value
): [Value, () => void]
*/
export function useReducerAtom<Value, Action>(
anAtom: PrimitiveAtom<Value>,
reducer: (v: Value, a?: Action) => Value,
scope?: Scope
): [Value, (action?: Action) => void]
export function useReducerAtom<Value, Action>(
anAtom: PrimitiveAtom<Value>,
reducer: (v: Value, a: Action) => Value,
scope?: Scope
): [Value, (action: Action) => void]
export function useReducerAtom<Value, Action>(
anAtom: PrimitiveAtom<Value>,
reducer: (v: Value, a: Action) => Value,
scope?: Scope
) {
const [state, setState] = useAtom(anAtom, scope)
const dispatch = useCallback(
(action: Action) => {
setState((prev) => reducer(prev, action))
},
[setState, reducer]
)
return [state, dispatch]
}