Skip to content

Instantly share code, notes, and snippets.

@cecigarcia
Created December 13, 2017 09:22
Show Gist options
  • Save cecigarcia/a9c51c8df10f82895e228bda2c834854 to your computer and use it in GitHub Desktop.
Save cecigarcia/a9c51c8df10f82895e228bda2c834854 to your computer and use it in GitHub Desktop.
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