MCPcopy
hub / github.com/NervJS/nerv / Consumer

Class Consumer

packages/nerv/src/create-context.ts:56–96  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

54
55 // tslint:disable-next-line: max-classes-per-file
56 class Consumer extends Component<ConsumerProps, ConsumerState<T>> {
57 static isContextConsumer = true
58 state = {
59 value: this.getContextValue()
60 }
61
62 context: {
63 [contextProp: string]: Emiter<T> | undefined
64 }
65
66 componentWillMount () {
67 const emiter = this.context[contextProp]
68 if (emiter) {
69 emiter.off(this.onUpdate)
70 }
71 }
72
73 componentDidMount () {
74 const emiter = this.context[contextProp]
75 if (emiter) {
76 emiter.on(this.onUpdate)
77 }
78 }
79
80 onUpdate = (value: T) => {
81 if (!objectIs(value, this.state.value)) {
82 this.setState({
83 value: this.getContextValue()
84 })
85 }
86 }
87
88 getContextValue (): T {
89 const emiter = this.context[contextProp]
90 return isUndefined(emiter) ? defaultValue : emiter.value
91 }
92
93 render () {
94 return onlyChild(this.props.children)(this.state.value)
95 }
96 }
97
98 return {
99 Provider,

Callers

nothing calls this directly

Calls 3

getContextValueMethod · 0.95
objectIsFunction · 0.90
setStateMethod · 0.80

Tested by

no test coverage detected