Skip to content

Instantly share code, notes, and snippets.

@KateKate
Last active May 23, 2019 18:16
class RenderProp extends React.Component {
state = defaultState;
axiosSource = null;
tryToCancel() {
if (this.axiosSource) {
this.axiosSource.cancel();
}
}
dispatch(action) {
this.setState(prevState => reducer(prevState, action));
}
fetch = () => {
this.tryToCancel();
this.axiosSource = axios.CancelToken.source();
axios
.get(this.props.url, {
cancelToken: this.axiosSource.token
})
.then(response => {
this.dispatch({ type: "fetched", payload: response.data });
})
.catch(error => {
this.dispatch({ type: "error", payload: error });
});
};
componentDidMount() {
this.fetch();
}
componentDidUpdate(prevProps) {
if (prevProps.url !== this.props.url) {
this.fetch();
}
}
componentWillUnmount() {
this.tryToCancel();
}
render() {
return this.props.children(this.state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment