mukeshphulwani66 / Instagram-clone-MERN-Stack

296 stars 212 forks source link

Issue while deleting the comment #18

Closed ChitrangSharma closed 3 years ago

ChitrangSharma commented 3 years ago

I was trying to create logic to delete the comments... the logic however working but there are some issues

node route to delete comment ==> router.delete("/deletecomment/:id/:comment_id", requireLogin,(req,res)=>{ const comment ={_id:req.params.comment_id}; Post.findByIdAndUpdate( req.params.id,{ $pull:{comments:comment}, }, { new:true, } ) .populate("comments.postedBy","_id name") .populate("postedBy","_id name") .exec((err, postComment)=>{ if(err || !postComment){ return res.status(422).json({error:err}); } else{ const result=postComment; res.json(result) } }); })

front end code const deleteComment =(postid,commentid)=>{ fetch(/deletecomment/${postid}/${commentid}`,{ method:"delete", headers:{ "Authorization":"Bearer "+localStorage.getItem("jwt") }, }).then((res)=>{res.json()}) .then((result)=>{ const newData = data.map((item)=>{ if(item._id ==result._id){ return result } else{ return item } }); window.location.reload() setData(newData); window.location.reload() }) }

// calling delete comment (Using material UI)

{record.postedBy.name} {record.text} {(item.postedBy._id || record.postedBy._id)== state._id && ( deleteComment(item._id,record._id)} style={{float:"right"}} /> )}

` This works but requires refresh if I did not referesh it complains ...... Unhandled Rejection (TypeError): Cannot read property '_id' of undefined after refreshing page the comment gets deleted anyone knows better approach or solution to make this fixed

ChitrangSharma commented 3 years ago

Closing the issue....... I got the temporary solution to just refresh the window after delete request