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

Commit

Permalink
fix: make sure that onToggle gets called after the update (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
Andarist authored and Kent C. Dodds committed Mar 25, 2018
1 parent bd6fa22 commit 07bcd2b
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {Component} from 'react'
import PropTypes from 'prop-types'

const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args))
const noop = () => {}

class Toggle extends Component {
static propTypes = {
Expand All @@ -12,7 +13,7 @@ class Toggle extends Component {
}
static defaultProps = {
defaultOn: false,
onToggle: () => {},
onToggle: noop,
}
state = {
on: this.getOn({on: this.props.defaultOn}),
Expand Down Expand Up @@ -69,19 +70,22 @@ class Toggle extends Component {
}

setOnState = (state = !this.getOn()) => {
if (this.getOn() !== state) {
this.props.onToggle(state, this.getTogglerStateAndHelpers())
}
this.setState({on: state})
const cb =
this.getOn() === state
? noop
: () => {
this.props.onToggle(state, this.getTogglerStateAndHelpers())
}
this.setState({on: state}, cb)
}

setOn = this.setOnState.bind(this, true)
setOff = this.setOnState.bind(this, false)
toggle = this.setOnState.bind(this, undefined)

componentWillReceiveProps(newProps) {
if (newProps.on !== this.props.on && newProps.on !== this.state.on) {
this.setOnState(newProps.on)
componentWillReceiveProps({on}) {
if (on !== this.props.on && on !== this.state.on) {
this.setOnState(on)
}
}

Expand Down

0 comments on commit 07bcd2b

Please sign in to comment.