Skip to content

Instantly share code, notes, and snippets.

@pocketjoso
Last active August 30, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocketjoso/deee25517824e8938a1956b212cfd3a0 to your computer and use it in GitHub Desktop.
Save pocketjoso/deee25517824e8938a1956b212cfd3a0 to your computer and use it in GitHub Desktop.
AuthenticationProtector HOC breaks HMR due to always re-mounted - why?
import React, { Component } from 'react'
import { connect } from 'react-redux'
// USING this component breaks our HMR - it does reload but local state is lost;
// due to that _this_ component always remounts - why?
// this is a SIMPLIFIED example of our
// HOC component for guarding access to Pages;
// heavily inspired by:
// https://codeburst.io/react-router-v4-unofficial-migration-guide-5a370b8905a#e85f
// usage:
// AuthenticationProtector(MyProtectedPage)
// NOTE: above usage breaks HMR for MyProtected page; removing the HOC wrapping it works as it should.
class AuthenticationProtector extends Component {
constructor () {
super()
this.state = { redirecting: true }
}
componentWillMount () {
this.checkAuthentication(this.props)
}
componentWillReceiveProps (nextProps) {
if (nextProps.location !== this.props.location) {
this.checkAuthentication(this.props)
}
}
checkAuthentication () {
// do checks, if the user don't have access to the page
if (needToRedirectToProtect) {
history.replace(/* redirect here */)
return
}
// if non of the authentication guards triggered
// - continue to the (base) page
this.setState({ redirecting: false })
}
render () {
const { redirecting } = this.state
// NOTE: always render the full component here ONLY FOR DEV,
// otherwise it gets unmounted and mounted again on HMR save,
// causing local state to be lost
if (IS_PROD && redirecting) {
// or perhaps a spinner here
return null
}
return <this.props.BaseComponent {...this.props} />
}
}
export default function (
BaseComponent
) {
function mapStateToProps ({ loggedInUser }) {
return { loggedInUser, BaseComponent }
}
return connect(mapStateToProps)(AuthenticationProtector)
}
// trying to resurrect HMR, to no avail (so far)....
export { AuthenticationProtector }
@pocketjoso
Copy link
Author

Note that the example component itself in the article I linked to (https://codeburst.io/react-router-v4-unofficial-migration-guide-5a370b8905a) also breaks HMR (inlining the HOC class definition inside the export function.

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