Skip to content

Commit

Permalink
Merge pull request openshift#2228 from kans/just-set-state
Browse files Browse the repository at this point in the history
Always set state in SafetyFirst...
  • Loading branch information
kans authored Apr 17, 2018
2 parents 5dc2642 + 4dc9d34 commit 9b06e3f
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions frontend/public/components/safety-first.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
import * as _ from 'lodash-es';
import * as React from 'react';

// React doesn't like it when you call setState unless your component is mounted
export class SafetyFirst<props, state> extends React.Component<props, state> {
/* eslint-disable no-undef */
unMounted_: boolean;
isMounted_: boolean;
setState_: Function;
/* eslint-enable no-undef */

constructor(props) {
super(props);
this.unMounted_ = false;
this.isMounted_ = false;
this.setState_ = this.setState;
this.setState = (...args) => {
this.setState = (arg0, arg1) => {
// NOP in the case that we are unmounting
if (this.unMounted_) {
return;
}

// business as usual...
if (this.isMounted_) {
return this.setState_(...args);
return this.setState_(arg0, arg1);
}

// We are in the constructor...
// https://reactjs.org/docs/react-component.html#setstate
const nextState = _.isFunction(arg0)
? arg0(this.state as any || {}, this.props)
: arg0;

this.state = Object.assign({}, this.state as any || {}, nextState);

if (_.isFunction(arg1)) {
return arg1();
}
// eslint-disable-next-line no-console
console.debug('SafetyFirst: Not setting state because component is not mounted.');
};
}

componentWillUnmount() {
this.unMounted_ = true;
this.isMounted_ = false;
}

Expand Down

0 comments on commit 9b06e3f

Please sign in to comment.