How to work with asynchrony using Reactjs

Asked

Viewed 78 times

0

I have the following code:

requireUsers = () => {
    this.users = database.ref('users')
    this.users.on('value', snapshot => {
        this.state.users = snapshot.val()
        Object.keys(snapshot.val()).map((value,key) => emails[key] = snapshot.val()[value].email)  
    })       
}

requireSeries = () => {
    Object.keys(emails).map((value,key) => emails[value] === email ? userId = Object.keys(this.state.users)[key] : "")
    this.series = database.ref(`users/${userId}/series/${this.props.match.params.genre}`)
    this.series.on('value', snapshot => {
        this.setState({
            series: snapshot.val()
        })
    })
}

componentDidMount = () => {
    auth.onAuthStateChanged(user => {
        if (user){
            email = user.email   
            this.setState({
                isLoggedIn: true,
                isLoading: false
            })              
            this.requireUsers()
            window.setTimeout(this.requireSeries, 2000)  
        }
    })         
}

I know that function window.setTimeout(this.requireSeries, 2000) will take some time, when the user registration number is large, but it is the only way I have found to load the data into the this.state.users. I tried to use async and await but it didn’t work. Someone knows how to use it async / await there?

1 answer

2

Like you tried to use async and await? await is a reserved word that serves to expect a Promise be resolved, if you do not create Promises, there is no way to use await.

async on the other hand serves as a function modifier. It causes all returns of a function to become one Promise.resove, and all the mistakes in one Promise.reject, that is, it is syntactic sugar.

But if you have many nested functions it is easier to work with classical syntax, especially if you want to return a result.

Playing by your code, I believe syntax would look like this:

requireUsers = () => new Promise((resolve , reject) => {
    this.users = database.ref('users');
    this.users.on('value', snapshot => {
        this.state.users = snapshot.val();
        Object.keys(snapshot.val()).map((value,key) => emails[key] = snapshot.val()[value].email);
        resolve(/*você pode retornar um valor aqui*/);
    });
});     

With async and await would look that way:

componentDidMount = async () => {
    auth.onAuthStateChanged(async user => {
        if (user) {
            email = user.email; 
            this.setState({
                isLoggedIn: true,
                isLoading: false
            });              
            await this.requireUsers();
            this.requireSeries();
        }
    });
}

Now if for some reason async and await does not work, because your framework is running synchronous functions behind the callbacks, you will have to use the methods then and catch, that are infallible:

componentDidMount = () => {
    auth.onAuthStateChanged(user => {
        if (user) {
            email = user.email; 
            this.setState({
                isLoggedIn: true,
                isLoading: false
            });
            /*v é o valor que você retornou, é irrelevante nesse exemplo*/
            this.requireUsers().then(v => this.requireSeries());
        }
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.