re: How to: mobx-state-tree + react + typescript VIEW POST

re: Hey Margarita, thanks for your post. Learned a lot. Btw, I still don't understand what you said, useInject is better than useStore when using com...

Great to hear it was helpful :)

When I implemented the useInject hook, I was thinking about having something similar to customizing inject with a mapper function, but with hooks. So if you have a more complicated app with lots of things in your store, or if you need to combine data from several stores, you might want to just extract all the data your component needs in a mapper function and then not care about how you get that data from the stores in your component.

For example,

const mapStore = ({ publishedPolls, participants }: RootStoreModel) => ({
 polls: publishedPolls.polls,
 totalNumberOfParticipants: participants.totalNumber

// in the component
const { polls, totalNumberOfParticipants } = useInject(mapStore)

Then you abstract away some details of your store implementation from your component's code. But I agree that it doesn't seem like a big problem to just use useStore, and since I am really used to redux and its mapStateToProps, I was trying to make it more comfortable for myself to develop with mst by using familiar concepts.

There is even a discussion about creating a similar useInject hook in this github issue.

However, when I tried the example above, I noticed an error in my implementation of useInject, which makes it confuse the return type from the mapper function because of this: (mapStore || defaultMapStore)(store), which is supposed to allow omitting mapStore parameter in the hook. On my way to fixing this, thanks a lot for making me notice the error! :)


Thanks for your detailed explanation!

useInject is a bit complicate to me, so I'm sticking to use useStore :-)

And another thing I found when I try your great example is enhanced the useStore with types:

export const useStore = () => useContext(StoreContext)


export const useStore: () => TRootStoreModel = () => useContext(StoreContext) as TRootStoreModel

Then it will be more convenience to use useStore with ts autocomplete feature!

code of conduct - report abuse