Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Created March 27, 2019 14:10
Show Gist options
  • Save akramsaouri/64f0d3c630ebc1efa51400df4b8bcc5f to your computer and use it in GitHub Desktop.
Save akramsaouri/64f0d3c630ebc1efa51400df4b8bcc5f to your computer and use it in GitHub Desktop.
import React from 'react'
import { withAppContext } from '../../app/hocs/WithAppContext';
/**
* withCachedObj
* HOC for reading/writing in-memory Context to/from localStorage
* useful for handling refresh/navigation etc..
* @param {React.Node} Component
*/
export default function withCachedObj(Component) {
return withAppContext(class extends React.Component {
cachedObj = null
componentWillMount() {
window.addEventListener('beforeunload', this.persistContextObj)
if (this.props.context.obj) {
// no need to recover saved obj if context is not empty
return
}
try {
// make attempt to recover saved obj from localStorage
this.cachedObj = JSON.parse(localStorage.getItem(LS_KEY))
if (this.cachedObj) {
// update root context with cached obj
this.props.context.setContext({ newObj: this.cachedObj })
}
} catch (e) {
this.cachedObj = null
}
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.persistContextObj)
}
persistContextObj = () => {
localStorage.setItem(LS_KEY, JSON.stringify(this.props.context.obj))
}
mergeCachedObj = () => {
return {
...this.props.context,
obj: { ...this.cachedObj }
}
}
render() {
const context = this.cachedObj ? this.mergeCachedObj() : { ...this.props.context }
return (
<Component {...this.props} context={context} />
)
}
})
}
export const LS_KEY = 'CONTEXT_OBJ'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment