1) Make sure you have any event listeners, setTimeouts or setIntervals
in componentDidMount
and remove them in componentWillUnmount
Example for listeners, setTimeouts and setIntervals:
componentDidMount() {
this.myTimer = setTimeout(() => {
// someCode here
}, 7000);
AppState.addEventListener('change', this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
clearTimeout(this.myTimer);
}
2) To cancel a fetch you have the following options:
Option A: Use AbortController
(In my opinion AbortController is much better than the old solution with isMounted
variable)
AbortController example:
import "abortcontroller-polyfill"; // in RN 0.60+ this will probably not be needed anymore
class App extends React.Component {
constructor() {
const AbortController = window.AbortController;
this.controller = new AbortController();
this.signal = this.controller.signal;
}
componentDidMount() {
const url = "https://myurl.com";
const signal = this.signal;
fetch(url, { signal })
.then(res => res.json())
.then(json => console.log(json))
.catch(err => {
// You can catch the error
// thrown by the polyfill here.
if (err.name == "AbortError") {
console.log("Fetch Aborted");
} else {
//Catch other errors.
}
});
}
componentWillUnmount() {
this.controller.abort();
}
/*--Rest of the code.--*/
}
Option B: Use Axios
and trigger a cancellation in componentDidMount
https://github.com/axios/axios#cancellation
Sources:
AbortController code:
https://github.com/facebook/react-native/issues/18115#issuecomment-420766665
How to cancel a fetch on componentWillUnmount
https://developer.mozilla.org/en-US/docs/Web/API/AbortController