aaronshaf/react-toggle

Double rendering -- this.state.checked is wrong

Mithgroth opened this issue · 0 comments

Helloes,
I've noticed a strange behavior in render function of index.js

I'm initiating my toggle with simple setup:
<Toggle onChange={ this.handleChange.bind(this) } checked={ this.state.launchOnMatchStart } />

handleChange sets my own component's state and writes to localStorage, then while initiating the Toggle again for the second time, I read the localStorage value if it exists.

In index.js, when I place my console.logs like this:

key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props;
      var className = _props.className;
      var _icons = _props.icons;
      console.log("node4: " + this.state.checked);
      var inputProps = _objectWithoutProperties(_props, ['className', 'icons']);
      var classes = (0, _classnames2.default)('react-toggle', {
        'react-toggle--checked': this.state.checked,
        'react-toggle--focus': this.state.hasFocus,
        'react-toggle--disabled': this.props.disabled
      }, className);
      console.log("node5: " + JSON.stringify(classes))

I get the following output:

app-3838027….js:2789 storage: false
app-3838027….js:2790 init: false
app-3838027….js:2824 render: false
vendor-3838027….js:9047 node3: false
vendor-3838027….js:9158 node4: false
vendor-3838027….js:9165 node5: "react-toggle"
app-3838027….js:2824 render: false
vendor-3838027….js:9158 node4: true
vendor-3838027….js:9165 node5: "react-toggle react-toggle--checked"

Notice the node4 and node5 repeating at the end.
node4 and node5 are from index.js - render, which gets triggered twice on init. And on the second trigger, this.state.checked changes value (from false to true), so my Toggle component is rendered as true although all my other variables log as false.

I also changed

_this.state = {
      checked: !(props.checked || props.defaultChecked),
      hasFocus: false
    };

in index.js - function Toggle() because although props.checked was correct, this.state.checked was always the opposite. With a single exclamation mark down, it's now correct; but the issue stands since it triggers render() twice.