Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Last active April 18, 2019 16:36
Show Gist options
  • Save VassilisPallas/e9a11b1506c7acb4756121cf1830d93b to your computer and use it in GitHub Desktop.
Save VassilisPallas/e9a11b1506c7acb4756121cf1830d93b to your computer and use it in GitHub Desktop.
High Order Component that removes all the xhr requests and returns a boolean to the component if it's mounted or not
import React from 'react';
import { connect } from 'react-redux';
import { withUnmounted } from '../components';
import propsTypes from './propsTypes';
import state from './state';
import dispatch from './dispatch';
class InvoiceList extends React.Component {
constructor(props) {
super(props);
this.state = { loading: false };
this._toggleLoading = this._toggleLoading.bind(this);
}
componentDidMount() {
this._toggleLoading();
this.props.fetchInvoices(this._toggleLoading);
}
_toggleLoading() {
if (!this.props.hasUnmounted) {
this.setState(({ loading }) => ({ loading: !loading }));
}
}
_renderLoading() {
if (this.state.loading) {
return <div>Loading...</div>;
}
return null;
}
render() {
return (
<div>
{this._renderLoading()}
</div>
);
}
}
InvoiceList.propTypes = propsTypes;
export default withUnmounted(
connect(
state,
dispatch
)(InvoiceList)
);
import React from 'react';
import { cancelRequests } from '../helpers/axiosInterceptor';
const withUnmounted = WrappedComponent => {
return class extends React.Component {
constructor(props) {
super(props);
this.isMount = true;
}
componentWillUnmount() {
this.isMount = false;
cancelRequests();
}
render() {
return <WrappedComponent isMount={this.isMount} {...this.props} />;
}
};
};
export default withUnmounted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment