Home > front end >  How to delete an item in an array that is stored in the backend server?
How to delete an item in an array that is stored in the backend server?

Time:09-07

Sorry I'm quite new to coding and I could not delete the item as clicking it would bring me to the page and error out. I tried to delete the item based on the product id but it doesn't work. When I refreshed the page, the item is still there.

The array in the server looks like that: [{"id":1,"name":"Apple","price":2,"createdAt":"2022","updatedAt":"2022"},{"id":2,"name":"Orange","price":1,"createdAt":"2022","updatedAt":"2022"}]

import "./App.css";
import React from "react";
import AddProduct from "./Components/AddProduct";
import SingleProduct from "./Components/SingleProduct";
import axios from "axios";
import { useState, useEffect } from "react";

export default function App() {
  const [openSingle, setOpenSingle] = useState(false);
  const [products, setProducts] = useState([]);
  const [currentId, setCurrentId] = useState("");

  const getInitialData = async () => {
    let initialAPICall = await axios.get(
      `${process.env.REACT_APP_API_SERVER}/products`
    );
    setProducts(initialAPICall.data);
  };

  useEffect(() => {
    getInitialData();
  }, []);

  const toggleView = (product) => {
    setOpenSingle(!openSingle);
    setCurrentId(product.id);
  };

  const createNewProduct = async (name, price) => {
    let product = {
      name,
      price,
    };
    let response = await axios.post(
      `${process.env.REACT_APP_API_SERVER}/products`,
      product
    );
    let newArray = [...products];
    newArray.push(response.data);
    setProducts(newArray);
  };

  const deleteClick = (id) => {
    var index = products
      .map(function (item) {
        return item.Id;
      })
      .indexOf(id);

    products.splice(index, 1);
  };

  return (
    <div className="App">
      <header className="App-header">
        {openSingle ? (
          <div>
            <SingleProduct toggle={toggleView} id={currentId} />
          </div>
        ) : (
          <div>
            <h4>Supermarket</h4>
            <h5>Products</h5>
            <div className="container">
              {products && products.length > 0 ? (
                products.map((product) => (
                  <div
                    className="product"
                    key={product.id}
                    onClick={() => toggleView(product)}
                  >
                    <h4>{product.name}</h4>
                    <h5>${product.price}</h5>
                    <button onClick={deleteClick(product.id)}>Delete</button>
                  </div>
                ))
              ) : (
                <p>Error</p>
              )}
            </div>
            <AddProduct addProduct={createNewProduct} />
          </div>
        )}
      </header>
    </div>
  );
}

My controller.js:

const BaseController = require("./baseController");

class ProductsController extends BaseController {
  constructor(model) {
    super(model);
  }

  async insertOne(req, res) {
    const { name, price } = req.body;
    try {
      const newProduct = await this.model.create({
        updated_at: new Date(),
        created_at: new Date(),
        name: name,
        price: price,
      });
      return res.json(newProduct);
    } catch (err) {
      return res.status(400).json({ error: true, msg: err });
    }
  }

  async getOne(req, res) {
    const id = req.params.productId;
    try {
      const output = await this.model.findByPk(id);
      return res.json(output);
    } catch (err) {
      console.log(err);
      return res.status(400).json({ error: true, msg: err });
    }
  }

  
}

module.exports = ProductsController;

How do I delete an item in this case? Thank you.

CodePudding user response:

To do this you will have to create a route on your express server that handles the deletion of an element in the array.This route uses the 'POST' method to send to the server the name of the item to remove from the array. The on the server you find will check to see if an item that matches the one sent is present in the array and deletes it. For this you can use forEach to find the item and remove it from the array.

    myArray.forEach((item,index) => {
if(item === itemToDelete){
myArray.splice(index, 1);
})
  • Related