Skip to content
This repository has been archived by the owner on Nov 26, 2018. It is now read-only.

Commit

Permalink
refactor(withState): simplify the implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieuprat committed Feb 28, 2017
1 parent 9958990 commit 7c526b7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 22 deletions.
6 changes: 3 additions & 3 deletions src/__tests__/withState.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('withState', () => {
expect(dummy.prop('pass')).toBe('through')
})

it('also accepts a non-function, which is passed directly to setState()', () => {
it('accepts a non-function, which is passed directly to setState()', () => {
const Counter = withState('counter', 'updateCounter', 0)(Dummy)
const dummy = mount(<Counter />).find(Dummy)
const { updateCounter } = dummy.props()
Expand All @@ -28,7 +28,7 @@ describe('withState', () => {
expect(dummy.prop('counter')).toBe(18)
})

it('also accepts initialState as function of props', () => {
it('accepts initialState as function of props', () => {
const Counter = withState(
'counter',
'updateCounter',
Expand All @@ -43,7 +43,7 @@ describe('withState', () => {
expect(dummy.prop('counter')).toBe(3)
})

it('should be merged with other hoc', () => {
it('is merged with other HOCs', () => {
const Component = compose(
withProps({ initialCounter: 1 }),
withState(
Expand Down
33 changes: 14 additions & 19 deletions src/withState.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,31 +45,26 @@ import updateProps from './utils/updateProps'
*/
const withState = (stateName, stateUpdaterName, initialState) =>
updateProps((next) => {
let previousProps
let previousStateValue
let props
let state

const updateState = (nextState) => {
update(previousProps, callOrUse(nextState, previousStateValue))
}

const update = (props, stateValue) => {
const stateUpdater = (nextState) => {
state = callOrUse(nextState, state)
next({
...props,
[stateName]: stateValue,
[stateUpdaterName]: updateState,
[stateName]: state,
[stateUpdaterName]: stateUpdater,
})

previousStateValue = stateValue
previousProps = props
}

return (props) => {
update(
props,
!previousProps
? callOrUse(initialState, props)
: previousStateValue,
)
return (nextProps) => {
if (!props) state = callOrUse(initialState, nextProps)
props = nextProps
next({
...props,
[stateName]: state,
[stateUpdaterName]: stateUpdater,
})
}
})

Expand Down

0 comments on commit 7c526b7

Please sign in to comment.