File tree Expand file tree Collapse file tree 4 files changed +28
-4
lines changed Expand file tree Collapse file tree 4 files changed +28
-4
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,15 @@ const Demo = () => {
18
18
< pre> {JSON .stringify (state, null , 2 )}< / pre>
19
19
< button onClick= {() => setState ({hello: ' world' })}> hello< / button>
20
20
< button onClick= {() => setState ({foo: ' bar' })}> foo< / button>
21
+ < button
22
+ onClick= {() => {
23
+ setState ((prevState ) => ({
24
+ count: prevState .count === undefined ? 0 : prevState .count + 1 ,
25
+ }))
26
+ }}
27
+ >
28
+ count
29
+ < / button>
21
30
< / div>
22
31
);
23
32
};
Original file line number Diff line number Diff line change @@ -11,6 +11,15 @@ const Demo = () => {
11
11
< pre > { JSON . stringify ( state , null , 2 ) } </ pre >
12
12
< button onClick = { ( ) => setState ( { hello : 'world' } ) } > hello</ button >
13
13
< button onClick = { ( ) => setState ( { foo : 'bar' } ) } > foo</ button >
14
+ < button
15
+ onClick = { ( ) => {
16
+ setState ( ( prevState ) => ( {
17
+ count : prevState . count === undefined ? 0 : prevState . count + 1 ,
18
+ } ) )
19
+ } }
20
+ >
21
+ count
22
+ </ button >
14
23
</ div >
15
24
) ;
16
25
} ;
Original file line number Diff line number Diff line change 1
1
import * as React from 'react' ;
2
2
3
- export type UseState = < T > ( initialState : T | ( ( ) => T ) ) => [ T , ( newState : T ) => void ] ;
3
+ export type UseState = < T > ( initialState : T | ( ( ) => T ) ) => [ T , ( newState : T | ( ( newState ) => T ) ) => void ] ;
4
4
export const useState : UseState = ( React as any ) . useState ;
5
5
6
6
export type UseEffect = ( didUpdate : ( ) => ( ( ( ) => void ) | void ) , params ?: any [ ] ) => void ;
Original file line number Diff line number Diff line change 1
1
import { useState } from './react' ;
2
2
3
- const useSetState = < T extends object > ( initialState : T = { } as T ) : [ T , ( patch : Partial < T > ) => void ] => {
3
+ const useSetState = < T extends object > ( initialState : T = { } as T ) : [ T , ( patch : Partial < T > | Function ) => void ] => {
4
4
const [ state , set ] = useState < T > ( initialState ) ;
5
5
const setState = ( patch ) => {
6
- Object . assign ( state , patch ) ;
7
- set ( state ) ;
6
+ if ( patch instanceof Function ) {
7
+ set ( ( prevState ) => {
8
+ return Object . assign ( state , patch ( prevState ) )
9
+ } )
10
+ } else {
11
+ Object . assign ( state , patch ) ;
12
+ set ( state ) ;
13
+ }
8
14
} ;
9
15
10
16
return [ state , setState ] ;
You can’t perform that action at this time.
0 commit comments