Everything works fine, but I have this warning Expected to return a value at the end of arrow function array-callback-return
. I tried using forEach
instead of map
, but then <CommentItem />
doesn't even show. How do I fix this?
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"/> ) // return } // if-statement }) // map-function } // map-function __begin </div> // comment.id ) // return
How do I fix this? 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. The warning indicates that you're not returning something at the end of your map arrow function in every case.
Arrow functions can have either a concise body or the usual block body. In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.
The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.
Arrow functions may implicitly return values by simply omitting the curly braces that traditionally wrap a function's body if their body only contains a single expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With