Skip to content

Commit

Permalink
Support updater function in setState
Browse files Browse the repository at this point in the history
  • Loading branch information
eirikurn committed Feb 13, 2018
1 parent 5951226 commit 4a898bf
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ describe('reactTreeWalker', () => {

componentWillMount() {
this.setState({ foo: 'bar' })
this.setState((state, props) => ({ other: `I am ${props.value} ${state.foo}` }))
}

render() {
Expand All @@ -109,8 +110,8 @@ describe('reactTreeWalker', () => {
}
}

return reactTreeWalker(<Baz />, () => true).then(() => {
const expected = { foo: 'bar' }
return reactTreeWalker(<Baz value="foo" />, () => true).then(() => {
const expected = { foo: 'bar', other: 'I am foo bar' }
expect(actual).toMatchObject(expected)
})
})
Expand Down
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ export default function reactTreeWalker(

// Make the setState synchronous.
instance.setState = newState => {
if (typeof newState === 'function') {
// eslint-disable-next-line no-param-reassign
newState = newState(
instance.state,
instance.props,
instance.context,
)
}
instance.state = Object.assign({}, instance.state, newState)
}

Expand Down

0 comments on commit 4a898bf

Please sign in to comment.