I have an initial state like so:
const initState = {
posts: data
}
now posts is something like :
[
{
"id": "",
"text": "",
"slug": "",
"title": "",
"comments": []
},
//some more here
]
So what I want to do is, when dispatch is fired I want to add new comments to that specific comments array. This is how I do it:
if (action.type === "ADD_COMMENT") {
let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
let index = state.posts.indexOf(findPost);
console.log(findPost);
return {
...state,
posts: [...state.posts,
state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
}
}
Even though my app works completely fine I have a problem with the redux state. Because everytime action is happened it adds new comments in to that specific array along with a new array in to state.
So in case of firing new action I do get something like this:
[
{
"id": "",
"text": "",
"slug": "",
"title": "",
"comments": ["comment here"]
},
[
{
"comments": ["comment here"]
},
//some more here
]
]
In each click it creates a new entry in to my state which I don't want at all. How can I make it possible that it only adds the comments in to that specific array but not as separate entry?