Cancelable fetch within a react native app
npm i --save react-native-cancelable-fetch
const fetch = require('react-native-cancelable-fetch');
// Make fetch request
fetch('http://localhost/', null, 1)
.then(res => res.json())
.then(data => {
console.log(data);
});
// Cancel request
fetch.abort(1);
Use object
for tag
const fetch = require('react-native-cancelable-fetch');
...
const Movies = React.createClass({
componentDidMount() {
// fetch movies
fetch(REQUEST_URL, null, this)
.then((response) => response.json())
.then((response) => this.setState({
dataSource: this.state.dataSource.cloneWithRows(response.movies),
loaded: true,
}));
},
componentWillUnmount() {
// Cancel request
fetch.abort(this);
},
...
});
- fetch(input, init, tag) make a request with a tag (
tag
can be number, string or object) - fetch.abort(tag) cancel request by tag