Skip to content

Commit

Permalink
prevent calling setState after component unmount
Browse files Browse the repository at this point in the history
  • Loading branch information
meriadec committed Mar 7, 2016
1 parent b83034a commit 081b916
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/portal.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default class Portal extends React.Component {
document.removeEventListener('touchstart', this.handleOutsideMouseClick);
}

this.closePortal();
this.closePortal(true);
}

shouldComponentUpdate(nextProps, nextState) {
Expand Down Expand Up @@ -108,15 +108,17 @@ export default class Portal extends React.Component {
this.props.onOpen(this.node);
}

closePortal() {
closePortal(isUnmounted = false) {
const resetPortalState = () => {
if (this.node) {
ReactDOM.unmountComponentAtNode(this.node);
document.body.removeChild(this.node);
}
this.portal = null;
this.node = null;
this.setState({active: false});
if (!isUnmounted) {
this.setState({active: false});
}
};

if (this.state.active) {
Expand Down
9 changes: 9 additions & 0 deletions test/portal_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@ describe('react-portal', () => {
unmountComponentAtNode(div);
assert(props.onClose.calledOnce);
});

it('should not call this.setState() if portal is unmounted', () => {
const div = document.createElement('div');
const props = {isOpened: true};
const wrapper = render(<Portal {...props}><p>Hi</p></Portal>, div);
spy(wrapper, 'setState');
unmountComponentAtNode(div);
assert.equal(wrapper.setState.callCount, 0);
});
});

describe('openByClickOn', () => {
Expand Down

0 comments on commit 081b916

Please sign in to comment.