Spiderweb
Spiderweb

Reputation: 39

React Native Do not use setState in componentDidMount (react/no-did-mount-set-state)

playing with react native and API I've faced this kind of issue: Do not use setState in componentDidMount (react/no-did-mount-set-state) Who knows the reason behind?

Here my piece of code Home.js

  state = {
    users: []
  }

  async componentDidMount() {
    const users = await ajax.fetchUsers();
    this.setState({users});
  }

Here FetchData.js

async fetchUsers() {
        try {
                let response = await fetch(URI + '/users');
                let responseJsonData = await response.json();
                return responseJsonData;
            }
        catch(e) {
            console.log(e)
        }
    }

Upvotes: 2

Views: 1135

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075337

My guess is that you're getting that error because the tool in question doesn't realize you've added async to componentDidMount, so it thinks you're synchronously setting state in componentDidMount.

You shouldn't do that. componentDidMount is not defined as an async method in React.Component. Don't make methods async when they aren't defined that way by the class you're extending. Nothing handles the promise that you'd be returning if you made componentDidMount async.

Instead, use a wrapper async function (and handle errors!!):

componentDidMount() {
    (async() => {
        try {
            const users = await ajax.fetchUsers();
            this.setState({users});
        } catch (e) {
            // ...handle/report error here...
        }
    })();
}

Or even break it out as its own method:

componentDidMount() {
    this.loadInitialUsers(); // Note: No `await`
}

async loadInitialUsers() {
    // Important: This must not throw any errors, because nothing handles
    // the promise rejection that would create
    try {
        const users = await ajax.fetchUsers();
        this.setState({users});
    } catch (e) {
        // ...handle/report error here...
    }
}

Upvotes: 4

Related Questions