Skip to content

Instantly share code, notes, and snippets.

@zrod
Last active August 20, 2017 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zrod/f241cb1c3c9e31fb67153ec5f8f9f28e to your computer and use it in GitHub Desktop.
Save zrod/f241cb1c3c9e31fb67153ec5f8f9f28e to your computer and use it in GitHub Desktop.
// object structure
{
id: '57dce89f84bec9ff038b456d',
slug: 'toronto',
country: {
id: '564e85d284bec915048b4568'
},
views: 14,
comments: [
{
"id": 1,
"user": {
id: '5699ab5e84bec978048b4ee0'
},
"comment": "blalba bla bla bla",
"created_at": "08/07/2017",
"hearts": 5,
"replies": []
}, {
"id": 2,
"user": {
id: '57ccf5ac84bec901118b4568'
},
"comment": "bla bla bla bla..",
"created_at": "08/08/2017",
"hearts": 3,
"replies": [
{
"id": 3,
"user": {
id: '5699ab5e84bec978048b4567'
},
"comment": "bla lba bla!",
"created_at": "08/11/2017",
"hearts": 0,
"replies": []
}
]
}
]
}
/**
* Uncaught Error: A state mutation was detected inside a dispatch, in the path: `itineraries.0.comments.0`.
* Take a look at the reducer(s) handling the action
* {"type":"ITINERARY_SUBMIT_COMMENT","payload":{"resourceId":"57dce89f84bec9ff038b456d","body":"dsfsdfdsfdsf","parent":1}}
*/
export default function injectComment(itinerary, parentId, newComment) {
for (let i in itinerary.comments) {
if (itinerary.comments[i].id == parentId) {
// Add comment to existing "replies" array
let modifiedComment = {
...itinerary.comments[i],
...{
replies: [...itinerary.comments[i].replies, newComment]
}
};
let comments = itinerary.comments.slice(); // <-- magic! (or map)
comments.splice(i, 1, modifiedComment);
return Object.assign({}, itinerary, {comments: comments});
}
// ...
}
return itinerary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment