Search code examples
react-nativeexpoes6-promisereact-state-management

setState() in componentDidMount() throwing an error in APK


I'm currently working on a project, using Expo 35 (or React Native 0.59)

My code works when tested in IOS simulator and ADV, using expo start.

However, it somehow throws an error and closes abruptly by itself when tested in APK (expo build:android).

Here's my code.

  componentDidMount() {

        Promise.all([
            4~5 Axios requests...             
        ])
            .then(() => {

                this.setState({
                    ...
                    loaded: true,
                    ...
                });
            })

    }

Any idea to fix the issue?


Solution

  • componentDidMount launches before rendering the component and setState will re-render the component and it will trigger an extra rendering, but it will happen before the app updates the screen and it's wrong.

    You can do something like this instead:

    _execute = ()=>{
       Promise.all([
                4~5 Axios requests...             
            ])
                .then(() => {
    
                    this.setState({
                        ...
                        loaded: true,
                        ...
                    });
                })
    }
    
    componentDidMount() {
        this._execute()
    }