Skip to content

Commit

Permalink
feat: allow useSetState setter to accept function
Browse files Browse the repository at this point in the history
* make setState of useSetState accept function argument

* update storybook
  • Loading branch information
clumsyme authored and streamich committed Nov 2, 2018
1 parent 819bd54 commit bfd114a
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 4 deletions.
9 changes: 9 additions & 0 deletions docs/useSetState.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ const Demo = () => {
<pre>{JSON.stringify(state, null, 2)}</pre>
<button onClick={() => setState({hello: 'world'})}>hello</button>
<button onClick={() => setState({foo: 'bar'})}>foo</button>
<button
onClick={() => {
setState((prevState) => ({
count: prevState.count === undefined ? 0 : prevState.count + 1,
}))
}}
>
count
</button>
</div>
);
};
Expand Down
9 changes: 9 additions & 0 deletions src/__stories__/useSetState.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ const Demo = () => {
<pre>{JSON.stringify(state, null, 2)}</pre>
<button onClick={() => setState({hello: 'world'})}>hello</button>
<button onClick={() => setState({foo: 'bar'})}>foo</button>
<button
onClick={() => {
setState((prevState) => ({
count: prevState.count === undefined ? 0 : prevState.count + 1,
}))
}}
>
count
</button>
</div>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/react.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';

export type UseState = <T>(initialState: T | (() => T)) => [T, (newState: T) => void];
export type UseState = <T>(initialState: T | (() => T)) => [T, (newState: T | ((newState) => T)) => void];
export const useState: UseState = (React as any).useState;

export type UseEffect = (didUpdate: () => ((() => void) | void), params?: any[]) => void;
Expand Down
12 changes: 9 additions & 3 deletions src/useSetState.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import {useState} from './react';

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

return [state, setState];
Expand Down

0 comments on commit bfd114a

Please sign in to comment.