i trying create reply to comments in my project, and I have some problems with adding comments to reducer, i am trying to add an reply without reloading the page.
My comments looks at:
JavaScript
x
22
22
1
[
2
id:
3
createdAt:
4
text:
5
comments: [
6
id:
7
createdAt:
8
text:
9
comments: [
10
id:
11
createdAt:
12
text:
13
comments: [],
14
15
id:
16
createdAt:
17
text:
18
comments: []
19
]
20
21
]
22
It’s my reducer, now i trying write to console:
JavaScript
1
12
12
1
[sendReplyRoutine.SUCCESS]: (state, action) => {
2
state.reply = initialState.reply;
3
4
function findById(arr, id, nestingKey) {
5
return arr.find(d => d.id === id)
6
|| findById(arr.flatMap(d => d[nestingKey] || []), id, 'comments')
7
|| 'Not found';
8
}
9
10
console.log(findById(state.post.comments, state.reply.replyCommentId, 'comments'));
11
}
12
I can’t think of how I can iterate through my array to add a comment to the block I need.
For example this is how i add the usual comment:
JavaScript
1
6
1
[sendCommentRoutine.SUCCESS]: (state, action) => {
2
state.comment = initialState.comment;
3
console.log(action.payload);
4
state.post.comments.unshift(action.payload);
5
}
6
Advertisement
Answer
If I understood your problem correctly, that might be helpful.
JavaScript
1
49
49
1
const comments = [
2
{
3
id: 1,
4
createdAt: '',
5
text: '',
6
comments: [
7
{
8
id: 2,
9
comments: [
10
{
11
id: 6,
12
comments: []
13
}
14
],
15
},
16
{
17
id: 3,
18
comments: [
19
{
20
id: 4,
21
comments: []
22
},
23
{
24
id: 5,
25
commensts: []
26
}
27
]
28
}
29
],
30
},
31
{
32
id: 7,
33
comments: []
34
}
35
];
36
37
const findById = (id, comments, idx = 0) => {
38
const item = comments[idx];
39
40
if (!item) return null;
41
if (item.id === id) return item;
42
43
const newComments = item.comments.length ? [comments, item.comments] : comments;
44
45
return findById(id, newComments, idx + 1);
46
};
47
48
console.log(findById(5, comments));
49
console.log(findById(7, comments));