When a user loads a blog post page, a post is fetched and its comments and subcomments are stored in the Redux state with the following structure:
forumPost: {
id: #,
data: {object},
comments: [
{
id: #,
data: {object},
comments: [
{
id: #,
data: {object},
comments: [...]
},
...
]
},{
id: #,
data: {object},
comments: [...]
},
...
}
When a user posts a new comment/subcomment, it is posted to the database and locally added to the Redux state. I am having problems with the second part
I created a function for finding the path to the parent comment of the comment being posted but am having trouble injecting the new comment into the current state.
const findPath = (comments, parentId) => {
let path = [];
const findIndex = (arry, count) => {
for (; count < arry.length; count++) {
if (arry[count].id === parentId) {
path = "forumPost.comments[" + count + "].comments";
return true;
}
if (arry[count].comments && arry[count].comments.length > 0) {
if (findIndex(arry[count].comments, 0)) {
path = path
.split("forumPost")
.join("forumPost.comments[" + count + "]");
return true;
}
}
}
};
findIndex(comments, 0);
return path; //Returns the parent's path as 'forumPost.comments[a].comments[b].comments'
};
I can create an entirely new state, add the new comment, and replace the old state, but doing so is expensive and (as I understand it) makes it impossible for a component to tell if the Redux state (mapped to props) has changed.
So, having done some research I have come to understand that redux treats updating and replacing the state differently and what I want to do is update the state.
- https://reactjs.org/docs/update.html
- Cleaner/shorter way to update nested state in Redux?
- Object spread vs. Object.assign
I’ve tried to use .update(), …spreads, and dot-prop, but haven’t been able to get them to work (most likely because I have been using them wrong)… and that’s why I am here. How do you update the state with a new comment object to one of the comments arrays of an unknown depth?
Also, I now know that its best practice to keep your redux state as shallow as possible. But the current structure is what it is.