I am new at working with React + MobX, so I don't fully understand how they work yet.
I want the function getUserDataFromAPI()
(in ProfileStore
) to be executed only when I go to http://localhost:3000/profile
and the component ProfileComponent
is loaded.
Here's what I have now:
Several Stores are initialized inside a rootStore.
class RootStore {
constructor() {
this.profileStore = new ProfileStore(this)
[other randomStores]
}
}
And then, in the ProfileStore.js
I have:
constructor(rootStore) {
this.rootStore = rootStore
runInAction('Load Profile', async () => {
await this.getUserDataFromAPI()
});
}
I still don't understand what runInAction does, but the main problem is that ProfileStore's constructor
gets executed regardless of the Component I am loading because it gets initialized with rootStore
.
How can I make that function to execute only when I navigate to /profile
and the Profile Component
is loaded?
What you want is a componentDidMount
method.
componentDidMount(){
this.profileStore = new ProfileStore(this)
}
Which will be executed once on component MOUNT, not on component creation.
https://reactjs.org/docs/react-component.html#componentdidmount