Answer the question
In order to leave comments, you need to log in
How to change nested comments (objects) in vuex store?
Added storage for comments, which looks like:
/**
* STATE
*
*/
const state = {
comments: [],
errors: [],
commentsLoaded: false
}
........
comments: [
{
id: 1,
replies : [
{
id: 2
},
{
id: 3,
replies: [
{
id: 4
}
]
}
]
},
{
id: 5,
replies: []
},
{
id: 6,
replies: []
}
],
ADD_REPLY(state,{comment_id,data}) {
state.comments.find(c => c.id === comment_id).replies.unshift(data);
},
state.comments.flatMap(comment => comment.replies).find(c => c.id === comment_id);
state.comments.flatMap(function loop(node) {
if (node.replies) {
return node.replies.flatMap(loop);
} else {
return [node];
}
})
Answer the question
In order to leave comments, you need to log in
Pass the comment object itself to the mutation instead of id - then you won't need to look for anything.
Or make a recursive search function, something like
const find = (arr, id) =>
(Array.isArray(arr) ? arr : []).reduce((found, n) =>
found || (n.id === id ? n : find(n.replies, id))
, null);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question