2019-01-25 00:39:15 +00:00
|
|
|
import React, { Component } from 'react'
|
|
|
|
|
|
|
|
const isServer = typeof window === 'undefined'
|
|
|
|
|
2019-01-25 15:43:12 +00:00
|
|
|
type State = Array<React.ReactElement<any>> | undefined
|
2019-01-25 00:39:15 +00:00
|
|
|
|
|
|
|
type SideEffectProps = {
|
2019-01-25 15:43:12 +00:00
|
|
|
reduceComponentsToState: (components: Array<React.ReactElement<any>>) => State,
|
|
|
|
handleStateChange?: (state: State) => void,
|
2019-01-25 00:39:15 +00:00
|
|
|
}
|
|
|
|
|
2019-01-25 15:43:12 +00:00
|
|
|
export default function withSideEffect() {
|
2019-01-25 00:39:15 +00:00
|
|
|
const mountedInstances: Set<any> = new Set()
|
|
|
|
let state: State
|
|
|
|
|
2019-01-25 15:43:12 +00:00
|
|
|
function emitChange(component: React.Component<SideEffectProps>) {
|
2019-01-25 00:39:15 +00:00
|
|
|
state = component.props.reduceComponentsToState([...mountedInstances])
|
2019-01-25 15:43:12 +00:00
|
|
|
if (component.props.handleStateChange) {
|
2019-01-25 00:39:15 +00:00
|
|
|
component.props.handleStateChange(state)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class SideEffect extends Component<SideEffectProps> {
|
|
|
|
// Used when server rendering
|
2019-01-25 15:43:12 +00:00
|
|
|
static rewind() {
|
2019-01-25 00:39:15 +00:00
|
|
|
const recordedState = state
|
|
|
|
state = undefined
|
|
|
|
mountedInstances.clear()
|
|
|
|
return recordedState
|
|
|
|
}
|
|
|
|
|
2019-01-25 15:43:12 +00:00
|
|
|
constructor(props: any) {
|
2019-01-25 00:39:15 +00:00
|
|
|
super(props)
|
|
|
|
if (isServer) {
|
|
|
|
mountedInstances.add(this)
|
|
|
|
emitChange(this)
|
|
|
|
}
|
|
|
|
}
|
2019-01-25 15:43:12 +00:00
|
|
|
componentDidMount() {
|
2019-01-25 00:39:15 +00:00
|
|
|
mountedInstances.add(this)
|
|
|
|
emitChange(this)
|
|
|
|
}
|
2019-01-25 15:43:12 +00:00
|
|
|
componentDidUpdate() {
|
2019-01-25 00:39:15 +00:00
|
|
|
emitChange(this)
|
|
|
|
}
|
2019-01-25 15:43:12 +00:00
|
|
|
componentWillUnmount() {
|
2019-01-25 00:39:15 +00:00
|
|
|
mountedInstances.delete(this)
|
|
|
|
emitChange(this)
|
|
|
|
}
|
|
|
|
|
2019-01-25 15:43:12 +00:00
|
|
|
render() {
|
2019-01-25 00:39:15 +00:00
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return SideEffect
|
|
|
|
}
|