Created
December 13, 2017 09:22
-
-
Save cecigarcia/a9c51c8df10f82895e228bda2c834854 to your computer and use it in GitHub Desktop.
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 cancelablePromise from "./cancelable-promise"; | |
class MyComponent extends Component { | |
state = { | |
data: [], | |
error: null, | |
}; | |
pendingPromises = []; | |
componentWillUnmount = () => | |
this.pendingPromises.map(p => p.cancel()); | |
appendPendingPromise = promise => | |
this.pendingPromises = [...this.pendingPromises, promise]; | |
removePendingPromise = promise => | |
this.pendingPromises = this.pendingPromises.filter(p => p !== promise); | |
handleOnClick = () => { | |
const wrappedPromise = cancelablePromise(fetchData()); | |
this.appendPendingPromise(wrappedPromise); | |
return wrappedPromise.promise | |
.then(() => this.setState({ data })) | |
.then(() => this.removePendingPromise(wrappedPromise)) | |
.catch(errorInfo => { | |
if (!errorInfo.isCanceled) { | |
this.setState({ error: errorInfo.error }); | |
this.removePendingPromise(wrappedPromise); | |
} | |
}); | |
} | |
render() { | |
const { data, error } = this.state; | |
if (error) { | |
return ( | |
<div className="error"> | |
There was an error fetching data: {error} | |
</div> | |
); | |
} | |
return ( | |
<div className="data"> | |
<button onClick={this.handleClick}>reload data!</button> | |
<ul className="data-list"> | |
{data.map((item, i) => <li key={i}>{item}</li>)} | |
</ul> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment