I'm trying to pass one mobX store to another store, following are my store codes:
Store class 1:
export default class APIKeyStore
{
@persist @observable apiKey = '****';
}
Store Class 2:
export default class ServiceCalls
{
@persist @observable apiKeysStore;
constructor(apiStore)
{
this.apiKeysStore = apiStore;
console.log('constructor', this.apiKeysStore.apiKey);
}
@action async initializeApp()
{
console.log('initializeApp', this.apiKeyStore.apiKey);
}
}
index.js:
import APIKeyStore from './models/APIKeyStore';
import ServiceCalls from './models/ServiceCalls';
const serviceCalls = new ServiceCalls(new APIKeyStore())
const stores = {
serviceCalls: serviceCalls
}
export default
{
...stores
};
Component file where I'm calling store 2's initializeApp() method:
@inject('serviceCalls')
@observer
class ZeroStepScreen extends Component
{
async componentWillMount()
{
try
{
console.log('componentWillMount', this.props.serviceCalls.apiKeysStore.apiKey);
await this.props.serviceCalls.initializeApp();
}
catch(e)
{
console.log(e);
}
}
}
In above classes, I have three console.log(..) declarations - where it reports proper results from the 2nd store's constructor, and the component's componentWillMount() methods.
When calling the same 2nd store class' initializeApp() method, this.apiKeysStore.apiKey always throws me cannot read property of undefined.
2nd class' constructor - console.log(this.apiKeysStore.apiKey) - OK
ZeroStepScreen - console.log(this.props.serviceCalls.apiKeysStore.apiKey) - OK
2nd class' initializeApp() - console.log(this.apiKeysStore.apiKey) - Error
I'm unable to understand what I'm doing wrong that the 2nd store class getting undefined when accessing this.apiKeysStore.apiKey when its constructor reported right, the component class reported right.
I'm not exactly sure about the fundamentals (to do these ways' of things) but following way in an end worked for me:
Probably using
asyncnot able me to access the class level observer directly.