Skip to content

Instantly share code, notes, and snippets.

@cdock1029
Last active August 4, 2018 17:41
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 cdock1029/fe1a88db5972b62bc67d2a255266b5f7 to your computer and use it in GitHub Desktop.
Save cdock1029/fe1a88db5972b62bc67d2a255266b5f7 to your computer and use it in GitHub Desktop.
import React from 'react'
import { AnyValue } from 'react-values'
interface SharedProps<T> {
// defaultValue?: T
// value?: T
// onChange?(value: T): void
children(params: {
value: T
set(value: T): void
}): JSX.Element | JSX.Element[] | null
storageKey: string
}
type SharedEvent = CustomEvent<{ storageKey: string }>
export class SharedValue<T> extends React.Component<SharedProps<T>> {
event: SharedEvent
constructor(props: SharedProps<T>) {
super(props)
this.event = new CustomEvent(props.storageKey, {
detail: { storageKey: props.storageKey },
})
}
componentDidMount() {
document.addEventListener(this.props.storageKey, this.handleEvent, false)
}
componentWillUnmount() {
document.removeEventListener(this.props.storageKey, this.handleEvent)
}
performStorageUpdate = (value: T) => {
window.localStorage.setItem(this.props.storageKey, JSON.stringify(value))
document.dispatchEvent(this.event)
}
handleEvent = (e: SharedEvent) => {
this.forceUpdate()
}
render() {
const { storageKey, children } = this.props
const storedValue = window.localStorage.getItem(storageKey)
const value = storedValue ? JSON.parse(storedValue) : undefined
return (
<AnyValue
value={value}
onChange={this.performStorageUpdate}
children={children}
/>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment