showing results for - "mern stack delete"
Melody
02 Jan 2018
1//MERN STACK DELETE
2
3//Route
4import { deletePost } from "../controllers/posts.js"
5router.delete("./:id", deletePost)
6
7//Controller
8export const deletePost = async (req, res) => {
9  const { id } = req.params;
10
11  if (!mongoose.Types.ObjectId.isValid(_id))
12  return res.status(404).send("No post with that id");
13
14  await PostMessage.findByIdAndRemove(id);
15
16  res.json({message: "Post deleted succesfully"})
17};
18
19//Server Side
20//API
21export const deletePost = (id) => axios.delete(`${url}/${id}`)
22
23//Actions
24export const deletePost = (id) => async (dispatch) => {
25  try {
26    await api.deletePost(id);
27    dispatch({ type: `DELETE`, payload: id });
28
29  } catch (error) {
30    console.log(error);
31  }
32};
33
34//Reducers
35    case "DELETE":
36      return post.filter((post) => post._id !== action.payload);
37      
38//Client - components
39import { useDispatch } from "react-redux"
40import { deletePost } from "../../../actions/post"
41
42
43  const dispatch = useDispatch();
44
45//Add event
46onClick={() => dispatch(deletePost(post._id))}
47
similar questions
queries leading to this page
mern stack delete