Last active
November 29, 2017 20:57
-
-
Save gnapse/ea53bcedf94a1a32b42bfb71e50817ff to your computer and use it in GitHub Desktop.
Avoiding calling setState on an unmounted React component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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