File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11import React from 'react' ;
2- import { useRestate , useAction } from '../src' ;
2+ import { useRestate , useAction , useDispatch } from '../src' ;
33
44export default function Component ( ) {
5- const [ restate , dispatch ] = useRestate ( ( state : { count : number } ) => {
5+ const dispatch = useDispatch ( ) ;
6+ const { count } = useRestate ( ( state : { count : number } ) => {
67 return { count : state . count } ;
78 } ) ;
89
910 const incrementAction = { type : 'INCREMENT' } ;
11+ const derementAction = { type : 'DECREMENT' } ;
1012 const increment = useAction ( incrementAction ) ;
1113
1214 return (
1315 < div >
14- < p > { restate . count } </ p >
16+ < p > { count } </ p >
1517 < a onClick = { increment } > Increment count</ a >
16- < a onClick = { ( ) => dispatch ( { type : 'DECREMENT' } ) } > Decrement count</ a >
18+ < a onClick = { ( ) => dispatch ( derementAction ) } > Decrement count</ a >
1719 </ div >
1820 ) ;
1921}
Original file line number Diff line number Diff line change @@ -17,9 +17,7 @@ const useStore = () => {
1717 return store ;
1818} ;
1919
20- export function useRestate < TState , USelector > (
21- selectFrom : ( state : TState ) => USelector ,
22- ) : [ USelector , Dispatch ] {
20+ export function useRestate < TState , TSelector > ( selectFrom : ( state : TState ) => TSelector ) : TSelector {
2321 const store = useStore ( ) ;
2422
2523 const [ restate , setRestate ] = useState ( ( ) => selectFrom ( store . getState ( ) ) ) ;
@@ -49,12 +47,18 @@ export function useRestate<TState, USelector>(
4947 [ store , selectFrom ] ,
5048 ) ;
5149
52- return [ restate , store . dispatch ] ;
50+ return restate ;
5351}
5452
55- export function useAction < TAction extends Action > ( action : TAction ) : ( ) => TAction {
53+ export function useDispatch < TAction extends Action > ( ) : Dispatch < TAction > {
5654 const store = useStore ( ) ;
57- const dispatch = useCallback ( ( ) => store . dispatch ( action ) , [ action ] ) ;
5855
59- return dispatch ;
56+ return store . dispatch ;
57+ }
58+
59+ export function useAction < TAction extends Action > ( action : TAction ) : ( ) => TAction {
60+ const dispatch = useDispatch ( ) ;
61+ const memoizedDispatch = useCallback ( ( ) => dispatch ( action ) , [ action ] ) ;
62+
63+ return memoizedDispatch ;
6064}
You can’t perform that action at this time.
0 commit comments