Saraband
Saraband

Reputation: 1590

setState after an API call inside a componentDidMount

I'm trying to implement a custom select which displays a list of languages fetched from an API.

I make the api call in the componentDidMount lifecycle hook and then update the state of my component according to the data I fetched.

Everything seems to work, yet I always get this error:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the LanguageSelect component.

Here's a snippet of my code:

export default class LanguageSelect extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
      languages: []
    };
  }

  // ...

  componentDidMount() {
    http.get('/api/parameters/languages')
      .then(

        // the Array.map is just to restructure the data fetched form the API
        data => this.setState({ languages : data.map(l => ({ label: l.LocalName, value: l.Code, })) }),

        // Error case
        error => console.error('Error: Languages data could not be fetched', error)
      )
  }

  // Render function
}

I don't understand, The only setState call I make is inside a componentDidMount() lifecycle thus is only executed when the component is mounted ?

Thanks in advance

Upvotes: 2

Views: 1059

Answers (1)

Giedrius
Giedrius

Reputation: 613

You could use isMounted() to check if it's mounted

if (this.isMounted()) {
  this.setState({...});
}

Although it's an anti pattern and you can find some proposals on best practice solutions here: https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

Upvotes: 2

Related Questions