Skip to content

Commit

Permalink
Merge pull request #108 from streamich/fix-usesetstate
Browse files Browse the repository at this point in the history
Fix usesetstate
  • Loading branch information
streamich committed Feb 17, 2019
2 parents d89bd54 + 524abe5 commit de933cf
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 12 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
2 changes: 1 addition & 1 deletion src/useOrientation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const useOrientation = (initialState: OrientationState = defaultState) => {
setState({angle, type});
} else if (window.orientation) {
setState({
angle: window.orientation,
angle: typeof window.orientation === 'number' ? window.orientation : 0,
type: ''
});
} else {
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 de933cf

Please sign in to comment.