Skip to content

Instantly share code, notes, and snippets.

@blairio
Last active January 14, 2016 18:55
Show Gist options
  • Save blairio/06ef01da8e2bb129bf74 to your computer and use it in GitHub Desktop.
Save blairio/06ef01da8e2bb129bf74 to your computer and use it in GitHub Desktop.
export default class MerchCoReports extends React.Component {
constructor(serverProps, context) {
super(serverProps, context);
this.state = {loggedIn: true, name: 'Bill'}
}
onLoggOutClicked = (e) => {
this.setState({loggedIn:false})
}
sessionExpired = (e) => {
this.setState({loggedIn:false, error: 'Expired'})
}
componentWillUpdate(nextProps, nextState) {
if (this.state.loggedIn && !nextState.loggedIn) {
nextState.name = '';
}
}
render() {
// Logout button, Name displayed etc....
}
}
@crobinson42
Copy link

 onLoggOutClicked = (e) => {
    this.setState({loggedIn:false, name : '' })
  }

  sessionExpired = (e) => {
    this.setState({loggedIn:false, name : '', error: 'Expired'})
  }

@crobinson42
Copy link

That's the correct way to go about this. You don't want to change the state in CWU because if the component grows and you need to find where something is happening, you'll be chasing you tail. HOWEVER, this is my opinion. There are other people who change the state in CWU... it's your preference to convention.

@blairio
Copy link
Author

blairio commented Jan 14, 2016

Thanks @crobinson42 for the response.
The crux is the repetition of name: '' I know it is simplistic here, but it is really a side affect of logging out, not necessarily of say, the session expiring. If I want to change the side affect then I have to update two places.

What do you think of something like this instead of using componentWillUpdate:

onLoggOutClicked = (e) => {
    this.logout()
  }

  sessionExpired = (e) => {
    this.logout();
    this.setState({error: 'Expired'})
  }

logout = () => {
   this.setState(loggedIn: false, name: '')
}

In this case things are DRY, but in the case of session expiry this.setState is called twice. Is that a bad thing? Is there a performance penalty? Is there two render and reconciliation cycles?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment