Skip to content

Commit

Permalink
fix: πŸ› fix useSetState after React update
Browse files Browse the repository at this point in the history
As reported in #107

Issues: #107
  • Loading branch information
streamich committed Feb 17, 2019
1 parent afbacac commit 524abe5
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 11 deletions.
4 changes: 2 additions & 2 deletions src/__stories__/useSetState.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ const Demo = () => {
<pre>{JSON.stringify(state, null, 2)}</pre>
<button onClick={() => setState({hello: 'world'})}>hello</button>
<button onClick={() => setState({foo: 'bar'})}>foo</button>
<button
<button
onClick={() => {
setState((prevState) => ({
count: prevState.count === undefined ? 0 : prevState.count + 1,
}))
}}
>
count
increment
</button>
</div>
);
Expand Down
12 changes: 3 additions & 9 deletions src/useSetState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,9 @@ import {useState} from 'react';

const useSetState = <T extends object>(initialState: T = {} as T): [T, (patch: Partial<T> | Function) => void]=> {
const [state, set] = useState<T>(initialState);
const setState = (patch) => {
if (patch instanceof Function) {
set((prevState) => {
return Object.assign(state, patch(prevState))
})
} else {
Object.assign(state, patch);
set(state);
}
const setState = patch => {
if (patch instanceof Function) set(prevState => Object.assign({}, prevState, patch(prevState)));
else set(Object.assign({}, state, patch));
};

return [state, setState];
Expand Down

0 comments on commit 524abe5

Please sign in to comment.