I am extracting array “comments” from an array of objects and when I trying to pass this array to a function I get this error “Cannot read property ‘comments’ of undefined”
here is a snippet from my code.
JavaScript
x
18
18
1
export const DISHES = [
2
{
3
id: 0,
4
name: "Uthappizza",
5
image: "assets/images/uthappizza.png",
6
category: "mains",
7
label: "Hot",
8
price: "4.99",
9
comments: [
10
{
11
id: 0,
12
rating: 5,
13
comment: "Imagine all the eatables, living in conFusion!",
14
author: "John Lemon",
15
date: "2012-10-16T17:57:28.556094Z"
16
},
17
{
18
in main class, I succeeded to get from DISHES array the right element
JavaScript
1
32
32
1
import { DISHES } from "../shared/dishes";
2
class Main extends Component {
3
constructor(props) {
4
super(props);
5
this.state = {
6
dishes: DISHES,
7
selectedDish: null
8
};
9
}
10
11
onDishSelect(dishId) {
12
this.setState({
13
selectedDishId: dishId
14
});
15
}
16
17
render() {
18
return (
19
20
<DishDetail
21
dish={
22
this.state.dishes.filter(
23
dish => dish.id === this.state.selectedDishId
24
)[0]
25
}
26
27
28
);
29
}
30
}
31
32
here I tried to parse “comments” but I couldn’t even to pass it to the function “renderComments” , but when I try to pass “this.props.dish” only it works fine
JavaScript
1
23
23
1
class DishDetail extends Component {
2
constructor(props) {
3
super(props);
4
this.renderComments = this.renderComments.bind(this);
5
}
6
7
renderComments(comments) {
8
return (
9
..
10
);
11
}
12
render() {
13
return (
14
<div className="col-12 col-md-5 m-1">
15
/*here is the problem*/
16
{this.renderComments(this.props.dish.comments)}
17
</div>
18
19
);
20
}
21
}
22
23
Advertisement
Answer
You are getting that error because this.state.selectedDishId
is undefined
and therefore the filter
doesn’t find a match.
You can add a check before going in the renderComments function like below :
JavaScript
1
2
1
this.props.dish && this.renderComments(this.props.dish.comments)
2
Component code
JavaScript
1
29
29
1
import React, { Component } from 'react';
2
3
class DishDetail extends Component {
4
constructor(props) {
5
super(props);
6
this.renderComments = this.renderComments.bind(this);
7
}
8
9
renderComments(comments) {
10
return comments.map((comment)=> {
11
return(
12
<p>
13
{comment.comment}
14
</p>
15
)
16
})
17
}
18
render() {
19
return (
20
<div className="col-12 col-md-5 m-1">
21
{this.props.dish && this.renderComments(this.props.dish.comments)}
22
</div>
23
24
);
25
}
26
}
27
28
export default DishDetail;
29
here is a complete stackblitz
Reference :