Skip to content
This repository was archived by the owner on Nov 27, 2020. It is now read-only.

Commit

Permalink
fix: only fire onToggle on external props change if it's different to…
Browse files Browse the repository at this point in the history
… internal on state to avoid double firing (#19)
  • Loading branch information
bslinger authored and Kent C. Dodds committed Mar 24, 2018
1 parent f8e32df commit bd6fa22
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
5 changes: 3 additions & 2 deletions src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,14 @@ test('onToggle gets called with fresh state in controlled prop scenario', () =>
expect(spy.mock.calls.length).toBe(1)
})

test('onToggle gets called when setOnState is called in controlled prop scenario', () => {
test('onToggle gets called on internal state change in controlled prop scenario', () => {
const spy = jest.fn()
const {setOn, setOff} = setup({on: false, onToggle: spy})
const {setOn, setOff, wrapper} = setup({on: false, onToggle: spy})
setOff()
expect(spy).not.toHaveBeenCalled()
setOn()
expect(spy).toHaveBeenLastCalledWith(true, expect.anything())
wrapper.setProps({on: true})
expect(spy.mock.calls.length).toBe(1)
})

Expand Down
8 changes: 3 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,9 @@ class Toggle extends Component {
setOff = this.setOnState.bind(this, false)
toggle = this.setOnState.bind(this, undefined)

componentDidUpdate(prevProps, prevState) {
const on = this.getOn()

if (this.getOn(prevState, prevProps) !== on) {
this.props.onToggle(on, this.getTogglerStateAndHelpers())
componentWillReceiveProps(newProps) {
if (newProps.on !== this.props.on && newProps.on !== this.state.on) {
this.setOnState(newProps.on)
}
}

Expand Down

0 comments on commit bd6fa22

Please sign in to comment.