Skip to content

Commit bfd114a

Browse files
clumsymestreamich
authored andcommitted
feat: allow useSetState setter to accept function
* make setState of useSetState accept function argument * update storybook
1 parent 819bd54 commit bfd114a

File tree

4 files changed

+28
-4
lines changed

4 files changed

+28
-4
lines changed

docs/useSetState.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@ const Demo = () => {
1818
<pre>{JSON.stringify(state, null, 2)}</pre>
1919
<button onClick={() => setState({hello: 'world'})}>hello</button>
2020
<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>
2130
</div>
2231
);
2332
};

src/__stories__/useSetState.story.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,15 @@ const Demo = () => {
1111
<pre>{JSON.stringify(state, null, 2)}</pre>
1212
<button onClick={() => setState({hello: 'world'})}>hello</button>
1313
<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>
1423
</div>
1524
);
1625
};

src/react.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as React from 'react';
22

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];
44
export const useState: UseState = (React as any).useState;
55

66
export type UseEffect = (didUpdate: () => ((() => void) | void), params?: any[]) => void;

src/useSetState.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import {useState} from './react';
22

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]=> {
44
const [state, set] = useState<T>(initialState);
55
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+
}
814
};
915

1016
return [state, setState];

0 commit comments

Comments
 (0)