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?
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));
});
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With