0

My component needs to use properties that I'm passing when I creating the component (OwnProps), plus it needs to use props from MobX Store. I know how to connect component that is using only Mobx Store or only OwnProps. But I can't find a way to have both. Here is an example I wrote. Help me, please.

// Main App.tsx inside Router
// Properties I passed here I'll call own props.
<Container
    {...match.params}
    id={match.id}
/>

// Container.tsx. Container logic and types are here.
// Own props

import { observer, inject } from 'mobx-react'

export interface ContainerOwnProps {
  id: number,
}

// Own props with connected MobX store
type ContainerProps = ContainerOwnProps & {
  store: ContainerStore
}

// In this decorator, I want to inject my MobX store and save my types.
// And this is doesn't work, cause I don't know how to pass ownProps argument when I export it below
const connector = (Component: React.FC<ContainerProps>, ownProps: ContainerOwnProps) =>
  inject((state: Stores) : ContainerProps => { // in Stores object I desided to place all my components stores
    return {
      ...ownProps,
      store: state.ContainerStore
    }
  })(observer(Component));
  
// Main react component. Which uses Own props and props from store
const Container: React.FC<ContainerProps> = 
  (props: ContainerProps) => {
    return (     
       <p id={props.id}>props.store.text</p>
    );
  }

// [Error] It would be nice to know how to put "ownProps" here
export default connector(Container, ownProps) 
  
  
PilgrimViis
  • 1,511
  • 2
  • 17
  • 21

1 Answers1

0

So, I researched it a bit. And I found out that the "inject" pattern is outdated. I end up using "mobx-react-lite" with hooks and react context. It's easy and corresponds to react best practice. Also, you can write your own hook to connect the store. The code looks something like this:

const storeContext = createContext(mobxStore)    
const useStore = () => useContext(storeContext)    
const store = useStore()
PilgrimViis
  • 1,511
  • 2
  • 17
  • 21