I'm trying to add an object to a nested array but am not sure how to achieve this using store / vuex. I have no problems updating the main comments array using a mutation but am stuck on how to specify which main comment to push the new reply object to. The pushReply mutations adds the reply to EVERY instance of a comment.
VUEX:
export const state = () => ({
comments: [
{
id: 1,
likes: 0,
postDate: '12/22/2021 1:25pm',
name: 'amyrobson',
img: '/img/avatars/image-amyrobson.png',
post: `Impressive! Though it seems the drag feature could be improved.
But overall it looks incredible. You've nailed the design and the
responsiveness at various breakpoints works really well.`,
replies: [
{
id: 1,
likes: 0,
postDate: '12/22/2021 1:25pm',
name: 'Reply One',
img: '/img/avatars/image-avatar.png',
post: `Lorem ipsum
dolor sit amet consectetur adipisicing elit. Veniam a aut quis
recusandae magnam tenetur porro autem minima aspernatur
voluptatum`,
},
],
},
],
})
export const mutations = {
pushComment(state, comment) {
state.comments.push(comment)
},
pushReply(state, comment) {
state.comments.forEach((item) => {
item.replies.push(comment)
})
},
}
component:
methods: {
addComment() {
this.isSending = true
// postDate
const newDate = new Date()
const currentDate = newDate.toLocaleDateString('en-US')
const currentTime = newDate.toLocaleTimeString([], {
timeStyle: 'short',
})
const createdAt = `${currentDate} ${currentTime}`
setTimeout(() => {
this.$store.commit('comments/pushComment', {
id: this.$store.state.comments.comments.length + 1,
likes: 0,
postDate: createdAt,
name: 'ramsesmiron',
img: this.image,
post: this.formValues.comment,
replies: [],
})
this.$formulate.reset('formAddComment')
this.isSending = false
}, 1000)
},
},
You should specify on which comment you want to add this reply object.
Either by passing the comment id to pushReply or by adding this id to the reply object (like parentId).
Then, in the pushReply function, find the comment by this id and add this reply to it.
You have several ways as this one:
const state = {
comments: [
{
id: 1,
replies: [],
parentId: null,
},
{
id: 2,
replies: [],
parentId: null,
},
{
id: 3,
replies: [],
parentId: null,
},
],
};
const reply = {
id: 1,
replies: [],
parentId: 2,
};
function pushReply(state, comment) {
if (null === comment.parentId) return; // handle this case, maybe throw an error
state.comments.find((item, i) => {
if (item.id === comment.parentId) {
state.comments[i].replies.push(comment);
}
});
}
pushReply(state, reply);
console.log(state);