I have Posts
and Comments
and I'm trying to build the UI for adding a comment to a post using React and Meteor. When I submit a comment, the new comment appears and then immediately disappears. When I refresh the page, the new comment is there.
Meteor.publish('post', function(postId) {
return Posts.find(postId);
});
Meteor.publish('comments.forPost', function(postId) {
const post = Posts.findOne(postId);
return Comments.find({_id: { $in : post.comments } } );
});
Meteor.methods({
'comments.insert'({ postId, content }) {
check(postId, String);
check(content, String);
const commentId = Comments.insert({
createdAt: new Date(),
userId: this.userId,
content,
});
Posts.update(postId, { $addToSet: { comments: commentId }});
});
In my React component I use createContainer
:
export default createContainer((props) => {
const id = props.params.id;
const postHandle = Meteor.subscribe('post', id);
const isLoading = !postHandle.ready();
Meteor.subscribe('comments.forPost', id);
const post = Posts.findOne(id);
const comments =
isLoading ? [] : Comments.find({_id: { $in: post.comments } }).fetch();
console.log(comments.length);
return {
comments,
isLoading,
question,
};
}, PostShow);
My console.log
statement prints the new length after adding a comment, and then prints the previous number.