Home > database >  Multiple delete function on server and frontend
Multiple delete function on server and frontend

Time:04-13

I am beginner and I have an app that looks like picture 1

After toggling on checkboxes I have my ids in array picture 2

After click on mass delete button I got an error (picture 3). And I got it because I pass an array but if I toggle only one everything works fine.

Delete function on frontend

const deleteProduct = async (selectedItems) => {
    console.log(selectedItems);
    dispatch({ type: DELETE_PRODUCT_BEGIN });
    try {
      await axios.delete(`http://localhost:5000/api/v1/${selectedItems}`);
      getProducts();
    } catch (error) {
      console.log(error.response);
    }
  };

Delete function on server

const deleteProduct = async (req, res) => {
  console.log(req.params.id);
  console.log(req.body.selectedItems);
  const { id: productId } = req.params;

  const product = await Product.findOne({ _id: productId });

  if (!product) {
    throw new Error(`No job with id : ${jobId}`);
  }

  await product.remove();
  res.status(200).json({ msg: "Success! Product removed" });
};

My route looks like

router.route("/:id").delete(deleteProduct);

Please help me to figure out how to make it

Server

import express from "express";
const app = express();
import cors from "cors";
import dotenv from "dotenv";
dotenv.config();
import morgan from "morgan";

import connectDB from "./db/connect.js";
import productsRoutes from "./routes/productsRoutes.js";

//middleware
import notFoundMiddleware from "./middleware/not-found.js";
import errorHandlerMiddleware from "./middleware/error-handler.js";

if (process.env.NODE_ENV !== "production") {
  app.use(morgan("dev"));
}

app.use(express.json());
app.use(cors());

app.get("/", (req, res) => {
  res.send("Welcome");
});

app.use("/api/v1", productsRoutes);

app.use(notFoundMiddleware);
app.use(errorHandlerMiddleware);

const port = 5000;

const start = async () => {
  try {
    await connectDB(process.env.MONGO_URL);
    app.listen(port, () => console.log(`Server is listening on port ${port}`));
  } catch (error) {
    console.log(error);
  }
};
start();

CodePudding user response:

Can you add your server app?

This error can be from the server routes.

From what i know it's maybe beacuse your route don't have a delete route :

router.delete('/:id', someFunc('deleteUser'), delete);

ref: www.tabnine.com/code/javascript/functions/express/Router/delete

  • Related