Answers for "mern stack delete"

0

mern stack delete

//MERN STACK DELETE

//Route
import { deletePost } from "../controllers/posts.js"
router.delete("./:id", deletePost)

//Controller
export const deletePost = async (req, res) => {
  const { id } = req.params;

  if (!mongoose.Types.ObjectId.isValid(_id))
  return res.status(404).send("No post with that id");

  await PostMessage.findByIdAndRemove(id);

  res.json({message: "Post deleted succesfully"})
};

//Server Side
//API
export const deletePost = (id) => axios.delete(`${url}/${id}`)

//Actions
export const deletePost = (id) => async (dispatch) => {
  try {
    await api.deletePost(id);
    dispatch({ type: `DELETE`, payload: id });

  } catch (error) {
    console.log(error);
  }
};

//Reducers
    case "DELETE":
      return post.filter((post) => post._id !== action.payload);
      
//Client - components
import { useDispatch } from "react-redux"
import { deletePost } from "../../../actions/post"


  const dispatch = useDispatch();

//Add event
onClick={() => dispatch(deletePost(post._id))}
Posted by: Guest on February-16-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language