How to migrate mobx-react 5 to 6 with correct typesafe injection?

Viewed 732

Now I am working with a TypeScript React with class component project and I am gradually migrating to react hooks.

Since mobx react 6 documents said that Store injecting is obsolete. How can I gradually migrate my React class components using old style injecting(@inject) while the project is using mobx-react 6?

There is a Migration guide with example as below code.

import { MobXProviderContext } from 'mobx-react'
function inject(selector, baseComponent) {
    const component = ownProps => {
        const store = React.useContext(MobXProviderContext)
        return useObserver(() => baseComponent(selector({ store, ownProps })))
    }
    component.displayName = baseComponent.name
    return component
}

The problem is what is the correct typesafe of this function. Thanks!

I have try this but I cannot figure baseComponent(selector({ store, ownProps }))) type correctly now.

const inject = <InProps, OutProps>(selector: (store: InProps) => OutProps) => {
    return <WrappedProps>(baseComponent: React.ComponentClass<WrappedProps> | React.FC<WrappedProps>) => {
        const component = (ownProps: WrappedProps) => {
            const store = React.useContext(storesContext)
            return useObserver(() => baseComponent(selector({ store, ownProps })))
        }
        component.displayName = baseComponent.name
        return component
    }
}
0 Answers
Related