chopeds
chopeds

Reputation: 317

How to execute a function after loading a component in Reactjs + MobX?

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/profileand the component ProfileComponent is loaded.

Here's what I have now:

Several Stores are initialized inside a rootStore.

RootStore.js

class RootStore {
    constructor() {
        this.profileStore = new ProfileStore(this)

        [other randomStores]
    }
}

And then, in the ProfileStore.js I have:

ProfileStore.js

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?

Upvotes: 0

Views: 1032

Answers (1)

sEver
sEver

Reputation: 2295

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

Upvotes: 1

Related Questions