简体   繁体   中英

React and Mobx - Load API data on load?

I have to validate that the user is logged in, using some token, that currently in the next example will already be set, for testing.

I have two options that I can think of.

Option 1

Do it on store's constructor:

export class MyStore {

    @observable token = "sometoken";
    @observable authenticated = false;

    constructor() {
        this.checkAuth();
    }

    @action
    checkAuth() {
        fetch("http://localhost:3001/validate/" + this.token)
            .then(res => res.json())
            .then(data => {
                this.authenticated = data.validated;
            });
            // catch etc
    }
}

Option 2:

Do it in my component's that uses the data, componentDidMount method.

Both of the ways work, but what is really the best practice to handle such state?

I would definitely go for the first option. If you don't always need the authentication - for example some parts are public - then just don't call this.checkAuth() in the store constructor. If all parts need authentication, then it looks good like this. Option 2 should be avoided because that would make unnecessary roundtrips to the server to re-validate a token which was already validated. And in general MobX gives great tools to minimize the use of lifecycle methods and write a cleaner code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM