I am trying to build the following: a forum where one can create a post, which triggers the ADD_POST, and the post is created, and added to the 'posts' object array. The each 'post' object is initialized with a 'comments' array that will hold comment texts ('commentTxt') entered inside that post.
let postReducer = function(posts = [], action) {
switch (action.type) {
case 'ADD_POST':
return [{
id: getId(posts), //just calls a function that provides an id that increments by 1 starting from 0
comments: [
{
id: getId(posts),
commentTxt: ''
}
]
}, ...posts]
Then when the user enters that post, there is a comment section where the user can enter a comment text and a new object would be added (via 'ADD_COMMENT') to the 'posts.comments' array
case 'ADD_COMMENT':
return posts.map(function(post){
//find the right 'post' object in the 'posts' array to update the correct 'comments' array.
if(post.id === action.id){
//update 'comments' object array of a 'post' object by adding a new object that contains 'commentTxt', and replaces the current 'comments' array
return post.comments = [{
id: action.id,
//new object is made with text entered (action.commentTxt) and added to 'post.comments' array
commentTxt: action.commentTxt
}, ...post.comments]
}
})
and would display it. And every time a new comment is added, a new would be rendered along with the previous comment objects in array. Would want to do something like the following:
{
this.props.post.comments.map((comment) => {
return <Comment key={comment.id} comment={comment} actions={this.props.actions}/>
})
}
I heard mutating state directly is not recommended, so I would appreciate any guidance or insight on how to properly do so.