UNPKG

1.31 kBTypeScriptView Raw
1import * as React from "react"
2import { observer as observerLite } from "mobx-react-lite"
3
4import { makeClassComponentObserver } from "./observerClass"
5import { IReactComponent } from "./types/IReactComponent"
6
7/**
8 * Observer function / decorator
9 */
10export function observer<T extends IReactComponent>(component: T, context: ClassDecoratorContext): void
11export function observer<T extends IReactComponent>(component: T): T
12export function observer<T extends IReactComponent>(component: T, context?: ClassDecoratorContext): T {
13 if (context && context.kind !== "class") {
14 throw new Error("The @observer decorator can be used on classes only")
15 }
16 if (component["isMobxInjector"] === true) {
17 console.warn(
18 "Mobx observer: You are trying to use `observer` on a component that already has `inject`. Please apply `observer` before applying `inject`"
19 )
20 }
21
22 if (
23 Object.prototype.isPrototypeOf.call(React.Component, component) ||
24 Object.prototype.isPrototypeOf.call(React.PureComponent, component)
25 ) {
26 // Class component
27 return makeClassComponentObserver(component as React.ComponentClass<any, any>) as T
28 } else {
29 // Function component
30 return observerLite(component as React.FunctionComponent<any>) as T
31 }
32}