Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix usesetstate #108

Merged
merged 2 commits into from
Feb 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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