How do I fix "Expected to return a value at the end of arrow function" warning?
Solution 1:
A map()
creates an array, so a return
is expected for all code paths (if/elses).
If you don't want an array or to return data, use forEach
instead.
Solution 2:
The warning indicates that you're not returning something at the end of your map arrow function in every case.
A better approach to what you're trying to accomplish is first using a .filter
and then a .map
, like this:
this.props.comments
.filter(commentReply => commentReply.replyTo === comment.id)
.map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);
Solution 3:
The easiest way only if you don't need return something it'ts just return null
Solution 4:
The problem seems to be that you are not returning something in the event that your first if
-case is false.
The error you are getting states that your arrow function (comment) => {
doesn't have a return statement. While it does for when your if
-case is true, it does not return anything for when it's false.
return this.props.comments.map((comment) => {
if (comment.hasComments === true) {
return (
<div key={comment.id}>
<CommentItem className="MainComment" />
{this.props.comments.map(commentReply => {
if (commentReply.replyTo === comment.id) {
return (
<CommentItem className="SubComment"/>
)
}
})
}
</div>
)
} else {
//return something here.
}
});
edit you should take a look at Kris' answer for how to better implement what you are trying to do.