anonymous
anonymous

Reputation: 186

Using match() for regex on react app getting error

componentDidMount(){
  axios.get('/sites/multiscreen/templates').then(res => {
    if(res.data.template_id.match(/^[a-z0-9]+$/i)){
      this.setState({
        templates: res.data,
      });
    }
  })
}

The error I'm getting is this:

Unhandled Rejection (TypeError): Cannot read property 'match' of undefined

Any help is appreciated!

Upvotes: 0

Views: 362

Answers (1)

Fred
Fred

Reputation: 3421

You have to make sure about res.data that it has value before calling match. I suggest you use this:

componentDidMount(){
  axios.get('/sites/multiscreen/templates').then(res => {
    if(!!res && 
       !!res.data &&
       !!res.data.template_id &&
       /^[a-z0-9]+$/i.test(res.data.template_id)) 
    {
      this.setState({templates: res.data});
    }
  })
}

Upvotes: 1

Related Questions