Skip to content

Instantly share code, notes, and snippets.

@mb8z
Last active October 2, 2018 14:52
Show Gist options
  • Save mb8z/85179e3de2272b81bc216f5a860123e4 to your computer and use it in GitHub Desktop.
Save mb8z/85179e3de2272b81bc216f5a860123e4 to your computer and use it in GitHub Desktop.
// Purposes:
// 1. For reseting a state on componentWillUnmount
// 2. For refetching data when :id in URL is changed
// It uses RequestCancellation from another gist file. More info here:
// https://stackoverflow.com/questions/52607886/react-requests-cancellation-on-page-change
import _ from 'lodash';
import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';
import RequestCancelation from '../services/requestCancelation';
const withReset = ({
mapStateToProps = () => ({}),
actions = {},
fetchMethodName,
cancelOngoingRequests = true,
}) => compose(
connect(mapStateToProps, actions),
lifecycle({
componentDidUpdate(prevProps) {
const { match: prevMatch } = prevProps;
const { match } = this.props;
if (prevMatch.url !== match.url) {
const recordID = _.get(match, 'params.id');
const method = this.props[fetchMethodName];
if (!recordID || !method) return;
method(recordID);
}
},
componentWillUnmount() {
if (cancelOngoingRequests) RequestCancelation.cancelRequests();
this.props.resetState();
},
}),
);
export default withReset;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment