A
A
Alexey Sklyarov2021-01-13 22:23:17
Vue.js
Alexey Sklyarov, 2021-01-13 22:23:17

How to change nested comments (objects) in vuex store?

Added storage for comments, which looks like:

/**
 * STATE
 * 
 */
const state = {
    comments: [],
    errors: [],
    commentsLoaded: false
}
........


comments is an array of comment objects where there is a property reply which is an array with the same comment objects:

Structure for example
comments: [
        {
            id: 1,
            replies : [
                {
                    id: 2
                },
                {
                    id: 3,
                    replies: [
                        {
                            id: 4
                        }
                    ]
                }
            ]
        },
        {
            id: 5,
            replies: []
        },
        {
            id: 6,
            replies: []
        }
    ],


What task do I solve: the user can add a response to some comment, respectively, after adding a comment to the server, I receive an added comment from the server and make a commit.
The problem is that I'm using the ID of the comment (to which the user has replied), looking for it in my array and pushing the new comment to comment.reply.

At first it looked like this:
ADD_REPLY(state,{comment_id,data}) {
        state.comments.find(c => c.id === comment_id).replies.unshift(data);
    },

And it worked for nesting depth = 1, as soon as I try to reply to a nested comment (nesting depth > 1), this function no longer works.

Tried searching for comment and using flatMap:
state.comments.flatMap(comment => comment.replies).find(c => c.id === comment_id);

but for some reason flatMap returns everything except the comment to which the answer is given (as I understand it, the problem is that the function does not show the last attachment).
I also tried something like this:
state.comments.flatMap(function loop(node) {
            if (node.replies) {
                return node.replies.flatMap(loop);
            } else {
                return [node];
            }              
        })


But as I understand it, I do not get direct access to the object, but only to a new one, that is, I cannot change it.

As the problem was googling, it became more and more common to meet messages that this is not an easy task, and indeed, it is necessary to store data differently. How to work with nesting of a large level?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-01-13
@0example

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 question

Ask a Question

731 491 924 answers to any question