setState pitfalls
suggest changeYou should use caution when using setState in an asynchronous context. For example, you might try to call setState in the callback of a get request:
class MyClass extends React.Component {
constructor() {
super();
this.state = {
user: {}
};
}
componentDidMount() {
this.fetchUser();
}
fetchUser() {
$.get('/api/users/self')
.then((user) => {
this.setState({user: user});
});
}
render() {
return <h1>{typeof this.state.user === 'string' ? this.state.user : (this.state.user.name || '')}</h1>;
}
}
This can cause problems. If the callback runs after the component has unmounted, this.setState still exists, but React warns and ignores the update. Make sure the setState can be cancelled. This example uses jQuery ($).
In this example, you might wish to cancel the XHR request when the component unmounts:
class MyClass extends React.Component {
constructor() {
super();
this.state = {
user: {},
xhr: null
};
}
componentWillUnmount() {
let xhr = this.state.xhr;
// Cancel the xhr request, so the callback is never called
if (xhr && xhr.readyState != 4) {
xhr.abort();
}
}
componentDidMount() {
this.fetchUser();
}
fetchUser() {
let xhr = $.get('/api/users/self');
xhr.then((user) => {
this.setState({user: user});
});
this.setState({xhr: xhr});
}
}
The jqXHR is saved in state. In componentWillUnmount you perform cleanup, including aborting the request. Keep the jqXHR itself; the return value of .then() is a promise and has no abort method. Also avoid rendering a plain object as a React child (<h1>{this.state.user}</h1> will throw in React 16). Render a field such as this.state.user.name, or a string.
You could also do something more complex. In this example, I’m creating a ‘stateSetter’ function that accepts the this object as an argument and prevents this.setState when the function cancel has been called:
function stateSetter(context) {
var cancelled = false;
return {
cancel: function () {
cancelled = true;
},
setState(newState) {
if (!cancelled) {
context.setState(newState);
}
}
}
}
class Component extends React.Component {
constructor(props) {
super(props);
this.setter = stateSetter(this);
this.state = {
user: 'loading'
};
}
componentWillUnmount() {
this.setter.cancel();
}
componentDidMount() {
this.fetchUser();
}
fetchUser() {
$.get('/api/users/self')
.then((user) => {
this.setter.setState({user: user});
});
}
render() {
return <h1>{typeof this.state.user === 'string' ? this.state.user : (this.state.user.name || '')}</h1>
}
}
This works because the cancelled variable is visible in the setState closure we created.