Skip to content

Commit 524abe5

Browse files
committed
fix: πŸ› fix useSetState after React update
As reported in #107 Issues: #107
1 parent afbacac commit 524abe5

File tree

2 files changed

+5
-11
lines changed

2 files changed

+5
-11
lines changed

β€Žsrc/__stories__/useSetState.story.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ 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
14+
<button
1515
onClick={() => {
1616
setState((prevState) => ({
1717
count: prevState.count === undefined ? 0 : prevState.count + 1,
1818
}))
1919
}}
2020
>
21-
count
21+
increment
2222
</button>
2323
</div>
2424
);

β€Žsrc/useSetState.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,9 @@ import {useState} from 'react';
22

33
const useSetState = <T extends object>(initialState: T = {} as T): [T, (patch: Partial<T> | Function) => void]=> {
44
const [state, set] = useState<T>(initialState);
5-
const setState = (patch) => {
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-
}
5+
const setState = patch => {
6+
if (patch instanceof Function) set(prevState => Object.assign({}, prevState, patch(prevState)));
7+
else set(Object.assign({}, state, patch));
148
};
159

1610
return [state, setState];

0 commit comments

Comments
Β (0)