Reputation: 405
I'm using React + Redux and I would like to create likes counter, but I have an error 'cannot read property 'map' of undefined'.
My Reducer's code:
const initialState = {
comments: [],
text: ''
}
case PUT_LIKE: {
return {
...state,
comments: state.comments.id === action.id ? state.comments.like + 1 : state.comments.like
}
}
//before this I have this case for posting comments
case ADD_COMMENT: {
let newComment = {
id: shortid.generate(),
text: state.text,
like: 0,
dislike: 0,
rating: 0
}
return {
...state,
comments: [newComment, ...state.comments],
text: ''
}
}
My Component's code (deleted some code to make it easier):
const ClientFeedback = ({comments,text,postComment,onCommentChange,putLike}) => {
return (
<div className='comments-container'>
{comments.map(m =>
<div key={m.id} className='comment-container'>
<div className='name'>
{nameImg}John
<span className='product-rating'>{rating}{rating}{rating}</span>
<SetDate />
</div>
<div className='text-comment'>
<span onClick={putLike} className='like'>{like}{m.like}</span>
<span className='dislike'>{dislike}{m.dislike}</span>
<div className='text'>{m.text}</div>
</div>
</div>)}
</div>
)
}
Container
class FeedbackContainer extends React.Component {
render() {
return (
<ClientFeedback {...this.props}/>
)
}
}
const mapStateToProps = (state) => ({
comments: state.feedbackReducer.comments,
text: state.feedbackReducer.text
})
export default compose(connect(mapStateToProps,{postComment,onCommentChange,putLike})(FeedbackContainer))
Action code:
export const putLike = (id) => ({type: 'PUT_LIKE', id})
sorry but this annoying: ( It looks like your post is mostly code; please add some more details
It looks like your post is mostly code; please add some more details)
Upvotes: 0
Views: 60
Reputation: 1872
I think this code snippet cause err.
case PUT_LIKE: {
return {
...state,
comments: state.comments.id === action.id ? state.comments.like + 1 : state.comments.like
}
}
You should try:
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comment => {
if(comment.id === action.id) return {...comment, like: comment.like + 1}
return comment
})
}
}
Upvotes: 0
Reputation: 743
Your reducer should do something like this:
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comment=>comment.id === action.id ? {...comment, like: comment.like+1} : comment)
}
}
Upvotes: 1
Reputation: 281736
The issue is that you are setting comments incorrectly on PUT_LIKE action. You need to map over the comments and set update the specific comments like value
case PUT_LIKE: {
return {
...state,
comments: state.comments.map(comments => comments.id === action.id ?
({...comments, like: comments.like + 1}) : comments)
}
}
Upvotes: 0