Skip to content

Commit

Permalink
Add updater argument
Browse files Browse the repository at this point in the history
  • Loading branch information
danedavid committed Feb 1, 2020
1 parent fc602e9 commit 7def56c
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions index.js
@@ -1,27 +1,35 @@
import { useReducer } from 'react';

const PATCH = '@action_types/PATCH';
const DERIVE = '@action_types/DERIVE';

const reducer = (state, action) => {
if ( action.type === PATCH ) {
return {
...state,
...action.payload,
};
switch ( action.type ) {
case PATCH:
return {
...state,
...action.payload,
};
case DERIVE:
return {
...state,
...action.updater(state),
};
default: console.error(`Unexpected action type: ${action.type}`); return state;
}
};

const useSetState = (initState) => {
const [_state, _dispatch] = useReducer(reducer, initState);
const _patchState = update => _dispatch({ type: PATCH, payload: update });
const _deriveState = updater => _dispatch({ type: DERIVE, updater });

const setState = (update) => {
const newState = {
..._state,
...update,
};

_patchState(newState);
const setState = (arg) => {
if ( typeof arg === 'function' ) {
_deriveState(arg);
} else {
_patchState(arg);
}
};

return [_state, setState];
Expand Down

0 comments on commit 7def56c

Please sign in to comment.