rsnext/packages/next/next-server/lib/side-effect.tsx
2020-06-11 22:09:06 +00:00

49 lines
1 KiB
TypeScript

import React, { Component } from 'react'
const isServer = typeof window === 'undefined'
type State = JSX.Element[] | undefined
type SideEffectProps = {
reduceComponentsToState: <T>(
components: Array<React.ReactElement<any>>,
props: T
) => State
handleStateChange?: (state: State) => void
headManager: any
inAmpMode?: boolean
}
export default class extends Component<SideEffectProps> {
emitChange = (): void => {
this.props.headManager.updateHead(
this.props.reduceComponentsToState(
[...this.props.headManager.mountedInstances],
this.props
)
)
}
constructor(props: any) {
super(props)
if (isServer) {
this.props.headManager.mountedInstances.add(this)
this.emitChange()
}
}
componentDidMount() {
this.props.headManager.mountedInstances.add(this)
this.emitChange()
}
componentDidUpdate() {
this.emitChange()
}
componentWillUnmount() {
this.props.headManager.mountedInstances.delete(this)
this.emitChange()
}
render() {
return null
}
}