Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react. From the code below, I tried to assess each blog post with comments. But I'm not able to get the comment property from the blog. If I do something like {blog.title} I get the title of the blog back on the browser. Since comments are associated with each post I try to get different properties of comment from the blog object (just as I specified in the code below) but the Value I'm getting is undefined. and have the following blog post and blog comment models.
class BlogComment(models.Model):
post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True)
name = models.CharField(max_length=200, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
dateCreated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user.username)
class BlogPost(models.Model):
...
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
body = models.TextField()
dateCreated = models.DateTimeField(auto_now_add=True)
And the serializers for both models are:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = BlogComment
fields = '__all__'
class BlogPostSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField(read_only=True)
class Meta:
model = BlogPost
fields = "__all__"
def get_comments(self, obj):
comments = obj.comment_set.all()
serializer = CommentSerializer(comments, many=True)
return serializer.data
<h2>{blog.title}</h2>
<img src={blog.image} />
<div variant='flush'>
{blog.comments.map((comment) => (
<div key={comment.id}>
<strong>{comment.name}</strong>
<p>{comment.dateCreated}</p>
<p>{comment.comment}</p>
</div>
))}
</div>
The comment API is functioning properly. In react, I'm able to add comments to each post using a form and the comments will appear in the database. But when I try to map through to display the comments of each blog post I get that error. How do I fix this?
CodePudding user response:
You can check the length of an array before the map. Or you can use optional chaining.
like this obj?.property
<h2>{blog?.title}</h2>
<img src={blog?.image} />
<div variant='flush'>
{blog?.post?.comments.map((comment) => (
<div key={comment?.id}>
<strong>{comment?.name}</strong>
<p>{comment?.dateCreated}</p>
<p>{comment?.comment}</p>
</div>
))}
</div>
