Skip to content

Instantly share code, notes, and snippets.

@gnapse
Last active November 29, 2017 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnapse/ea53bcedf94a1a32b42bfb71e50817ff to your computer and use it in GitHub Desktop.
Save gnapse/ea53bcedf94a1a32b42bfb71e50817ff to your computer and use it in GitHub Desktop.
Avoiding calling setState on an unmounted React component
import React, { Component } from ‘react’;
const noop = () => {};
export default class MyComponent extends Component {
state = { data: null, error: null };
handleSuccess = data => {
this.setState({ data });
};
handleFailure = error => {
this.setState({ error });
};
componentDidMount() {
fetch('/api/data')
.then(data => this.handleSuccess(data))
.catch(error => this.handleFailure(error));
}
componentWillUnmount() {
this.handleSuccess = noop;
this.handleFailure = noop;
}
render() {
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment