Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it safe to save state in React?

Let's say I have a react component that updates state from a form.

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      someCheckboxState: false,
    }
  }
  render() {
    return (
      <input onChange={this.handleChange} checked={this.state.someCheckboxState} />
    );
  }
  handleChange(event) {
    this.setState({
      someCheckboxState: event.target.checked,
    });
  }
}

Now I want to send that state to the server (or somewhere). If I just do this

handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  });
  SendStateToServer(JSON.stringify(this.state)); // BAD! Not yet mutated
}

I could put it in render but then it will get sent to the server on initial render as well as well and it seems silly to send state a function called render.

When is it okay to persist/serialize the state?

like image 584
gman Avatar asked Dec 10 '22 14:12

gman


2 Answers

The second argument of React's setState is a callback that is fired after the state transition is complete.

this.setState(newState, () => console.log(this.state));

So, in your case:

handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  }, () => {
    SendStateToServer(JSON.stringify(this.state));
  });
}
like image 176
Fabian Schultz Avatar answered Dec 23 '22 11:12

Fabian Schultz


Yes, setState() second parameter, perfect way to do such things.

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      someCheckboxState: false,
    }
  }
  render() {
    return ( < input type = "checkbox"
      onChange = {
        this.handleChange
      }
      checked = {
        this.state.someCheckboxState
      }
      />
    );
  }
  handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  }, () => { // do your work
      console.log(JSON.stringify(this.state));
    });
}
}

ReactDOM.render( < Form / > , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 25
prosti Avatar answered Dec 23 '22 11:12

prosti