Created
June 29, 2018 15:12
-
-
Save brendancol/5f71a0c06cfe65ddd22d319d5dabfd45 to your computer and use it in GitHub Desktop.
Abort Controller Polyfill Example
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'; | |
import './Fetch.css'; | |
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'; | |
const AbortController = window.AbortController; | |
const controller = new AbortController(); | |
const signal = controller.signal; | |
class Fetch extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
results: null, | |
status: null | |
} | |
} | |
handleRun = () => { | |
fetch('https://jsonplaceholder.typicode.com/photos', { signal }) | |
.then((resp) => resp.json()) | |
.then((data) => { | |
console.log("fetched"); | |
this.setState({ | |
results: JSON.stringify(data), | |
status: 'completed' | |
}); | |
}) | |
.catch((e) => { | |
console.log(e.message); | |
}); | |
} | |
handleAbort = () => { | |
controller.abort(); | |
console.log("aborting..."); | |
this.setState({ | |
status: 'aborted' | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>Fetch example</h1> | |
<div>Results: {this.state.results}</div> | |
<div>Status: {this.state.status}</div> | |
<br/> | |
<br/> | |
<button onClick={() => this.handleRun()}>Run</button> | |
<button onClick={() => this.handleAbort()}>Abort</button> | |
</div> | |
); | |
} | |
} | |
export default Fetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment