Store is returned as undefined #1748
-
Hi, I am using MST as part of the React Native Ignite template that provides a setup for MST. I have created a store as so: import { types } from 'mobx-state-tree';
import uuid from 'uuid';
export const TimeObject = types.model('TimeObject', {
id: types.identifier,
hour: types.string,
minutes: types.string,
amOrPm: types.enumeration(['AM', 'PM']),
timeStamp: types.number,
});
export const TimeStore = types
.model('TimeStore', {
time: types.map(TimeObject),
})
.actions(self => ({
addTime(json) {
const ids = [];
json.forEach(timeJson => {
if (!timeJson.id) {
timeJson.id = uuid.v1();
}
ids.push(timeJson.id);
self.time.put(timeJson);
});
return ids;
},
})); And have also passed it to my Rootstore so it looks like this: export const RootStoreModel = types.model('RootStore').props({
drugStore: types.optional(DrugStore, {
drugs: {},
}),
});
const RootStoreContext = createContext<RootStore>({} as RootStore);
export const RootStoreProvider = RootStoreContext.Provider;
export const useStores = () => useContext(RootStoreContext); However when I call this in a screen I keep getting timeStore.addTime is undefined. I am using it like this: const { timeStore } = useStores();
const timeId = timeStore.addTime([
{
hours,
mins,
amOrPm,
timeStamp: timeStamp.getTime(), //With correct values given for inputs
},
]); I am not really sure what is going wrong here so any help will be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I've tried to create a demo according to your description: https://codesandbox.io/s/1748-r8dkq?file=/src/models/UseStores.ts I think the culprit is this line:
You just asserted the type to fool the typing system But you need to actually create an instance for PS You can play with this part in the demo to compare different console output results with / without an actual instance |
Beta Was this translation helpful? Give feedback.
I've tried to create a demo according to your description: https://codesandbox.io/s/1748-r8dkq?file=/src/models/UseStores.ts
I think the culprit is this line:
const RootStoreContext = createContext<RootStore>({} as RootStore);
You just asserted the type to fool the typing system
But you need to actually create an instance for
RootStore
here!PS You can play with this part in the demo to compare different console output results with / without an actual instance