I am trying to dynamically display posts using aura:iteration. For each user's post there should be a list of comments (using a nested aura:iteration). I am getting my data in JSON format from an API call, and everything renders correctly, however I can't use the comments field for my second aura:iteration items.
JSON Data:
response: {
posts: [{
user: person1,
post: "foo",
comments: [
"comment 0",
"comment 0"
],
time: "yesterday"
},
{
user: person2,
post: "bar",
comments: [
"comment 1",
"comment 1"
],
time: "1 hr ago"
},
...
}
Aura:
<aura:attribute name="post_list" type="String[]" default="['N/A']" />
<ul class="slds-list--vertical-space-medium slds-m-left--xx-small">
<!-- POST BODY -->
<aura:iteration items="{!v.post_list}" var="post_item" indexVar="i">
<li class="post-element slds-item">
<div>
<div class="time-stamp">{!post_item.user}</div>
</div>
<div class="post-body">
<div>
<div class="post-text">{!post_item.post}</div>
<a href="{!v.btnURL}">See More</a>
</div>
<div class="post-time">{!post_item.time}</div>
</div>
<!-- / POST BODY -->
<!-- COMMENT PANEL -->
<div id="comment-panel" style="display: none" class="comment-panel">
<ul id="comment-list">
<aura:iteration items="{!post_item.comments}" var="post_comment">
<li>
<div class="comment-element">
<div class="comment-user">
John Cena
</div>
<div class="comment-text">
comment 0
</div>
</div>
</li>
</aura:iteration>
</ul>
<!-- / COMMENT PANEL -->
</li>
</aura:iteration>
Error Message:
AuraRuntimeException: no such property: comments
Best Answer
First, your
<aura:attribute>
is of the wrong type - it's aString
array.While I'm not certain that this will cause you problems, I advise you to change it to an
Object[]
type. The reason for this is that aString
can't really have any inner properties.If that doesn't work...
It's quite possible that for some posts there are no comments.
To get around this, you could pre-process the array to add an empty comments array for posts with no comments. This would prevent this sort of error occurring.
Eg: