Home > database >  Moving from MobX Provider to React context, typescript issue
Moving from MobX Provider to React context, typescript issue

Time:02-11

Trying to move from mobx's provider to React context. I have checked this article which suits pretty much exactly what I want https://shevchenkonik.com/blog/react-typescript-mobx

My use case includes a single registry object, which contains stores and services, which by using React context needs to be passed down the components.

I have it working 99%, however typescript is giving me a hard time. Below is a link to a sample. I have everything in 2 files to make it easier

https://codesandbox.io/s/minimal-observer-forked-sd88n

Although the UI is rendered, TS complains regarding the wrapped component not passing the props on line 53 (which are passed by the HOC).

Any help will be much appreciated Thanks

CodePudding user response:

This approach does not really work very well with TS, that's why the author "cleverly" omits types from the actual example where he tries to use it:

@withStore
@observer
class UserNameComponent extends Component< ??? > {
    render() {
        // props are completely untyped here
        const { store } = this.props;
        return (
            <div>{store.userStore.name}<div>
        )
    }
}

What you can do is mark properties as optional and then use null assertion operator ! to make TS skip null checking:

@withStore
@observer
class UserNameComponent extends Component<{ store?: Store }> {
    get store() {
       return this.props.store!
    }

    render() {
        return (
            <div>{this.store.userStore.name}<div>
        )
    }
}

Obviously it's not super type safe, because if you forget to wrap your component with decorator it will throw. That's why functional components are much better and easier to use in that case.

  • Related