bekanur98
bekanur98

Reputation: 520

How can I fix this problem with TypeError

I have typescript code. When click some button there must be working some func. That bounded with componentwillmount.

componentWillMount() {
    const { species } = this.props;
    const selectedSpecies =
    species.find(v => v.id == SPECIES_TYPE_CATTLE) || null;
    if (selectedSpecies) {
      this.onSpeciesSelect(selectedSpecies);
     }
}

TypeError: undefined is not an object(evaluating 'species.find')

Upvotes: 1

Views: 63

Answers (2)

Iman Rb
Iman Rb

Reputation: 797

selectedSpecies is probably result of an async action and its value is not available at the time that componentDidMount is doing its job. So it should have a default value or be checked before that has a value

Upvotes: 0

Vencovsky
Vencovsky

Reputation: 31565

You should check for species before doing .find.

const selectedSpecies = species ? species.find(v => v.id == SPECIES_TYPE_CATTLE) : null;

Upvotes: 4

Related Questions