Skip to content

Instantly share code, notes, and snippets.

@shilangyu
Last active July 24, 2019 21:31
Show Gist options
  • Save shilangyu/264a604443e922ba9972f31fd985a7cb to your computer and use it in GitHub Desktop.
Save shilangyu/264a604443e922ba9972f31fd985a7cb to your computer and use it in GitHub Desktop.
Strongly typed Mobx-React `inject` that separates injects from props
import { inject, IStoresToProps } from 'mobx-react'
import { Component } from 'react'
import UserStore from './UserStore' // import your stores
import AuthStore from './AuthStore' // import your stores
export const user = new UserStore()
export const auth = new AuthStore()
export interface IStores {
user: UserStore,
auth: AuthStore
}
export class ConnectedComponent<P, I, S = {}> extends Component<P, S> {
public get injects() {
return (this.props as any) as I
}
}
export function connect(...storeNames: Array<keyof IStores>): ReturnType<typeof inject>
export function connect<P, C, I>(
mapStoresToInjects: IStoresToProps<IStores, P, C, I>,
): ReturnType<typeof inject>
export function connect(): ReturnType<typeof inject> {
return inject(...arguments)
}
@shilangyu
Copy link
Author

Now instead of extending React.Component, extend the ConnectedComponent which takes one extra generic of injects interface. Now you can use a strongly typed connect (our new inject) and access the injected values in this.injects (no more optional props in interface definition). see more here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment