Skip to content

Instantly share code, notes, and snippets.

@marqu3z
Last active March 25, 2019 16:14
Show Gist options
  • Select an option

  • Save marqu3z/d94fb63d0090352e6f975b63d2b41882 to your computer and use it in GitHub Desktop.

Select an option

Save marqu3z/d94fb63d0090352e6f975b63d2b41882 to your computer and use it in GitHub Desktop.
// Side-effect inside constructor()
class Page extends React.Component {
static propTypes = {
fetch: PropTypes.func,
isPending: Proptypes.bool, // from store: It could be dirty from previous rendering
data: PropTypes.object, // from store: It could be dirty from previous rendering
resetState: PropTypes.func, // It will clean both isPending and data
}
constructor (props) {
super(props)
props.resetState()
}
/** @deprecated
componentWillUnmount () {
this.props.resetState()
}
**/
componentDidMount() {
this.props.fetch() // dipatch action -> sagas -> reducer
}
render () {
if (!this.props.isPending) {
return (<div>{this.props.data}</div>)
}
}
}
// Internal state with flag
class Page extends React.Component {
static propTypes = {
fetch: PropTypes.func,
isPending: PropTypes.bool, // from store: It could be dirty from previous rendering
data: Proptypes.object // from store: It could be dirty from previous rendering
}
constructor (props) {
super(props)
this.state = {
didFetch: false
}
}
componentDidUpdate(prevProps) {
if (prevProps.isPending === true && this.props.isPending === false) {
this.setState({ didFetch: true })
}
}
componentDidMount() {
this.props.fetch() // dipatch action -> sagas -> reducer
}
render () {
if (this.state.didFetch) {
return (<div>{this.props.data}</div>)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment