Working with asynchrony using ReactJS

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 this window.setTimeout(this.requireSeries, 2000) function will take some time, when the user registration number is large, but it is the only way I found to load the data in this.state.users . I tried to use async and await but it did not work. Does anyone know how you would use async / await there?

    
asked by anonymous 04.11.2018 / 04:32

1 answer

2

How did you try to use async and await ? await is a reserved word that is used to wait for Promise to be resolved, if you do not create promises, you can not use await.

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

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

To play 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 it would look like this:

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 then and catch methods, which 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());
        }
    });
}
    
04.11.2018 / 05:30