Home > Mobile >  REACT JS: Crud table delete
REACT JS: Crud table delete

Time:02-05

I have a parent component that sends props to a CRUD Table, i have a problem with deleting the items i want to delete the item with the selected id and i want to send both the email and id in the body of the request. i create the Info just to send it to the CRUD table to be shown because i don't want the entire pendingList to be shown. The id sent to the request when i click on deleteIcon={<IoTrashOutline style={{fontSize: '18px', color: 'red', cursor: 'pointer'}} onClick={() => handleDeleteProduct(info.id)} />} is undefined and i get it cause info is an array the problem is i'm not sure how to get the specific id of the item i want to delete and send it to the request. Any suggestions?

const UserNewDevice = () => {

    const [pendingList, setPendingList] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const email = localStorage.getItem("email")

    useEffect(() => {
        const fetchPendingList = async () => {
          setIsLoading(true);
          try {
            const res = await fetch('http://localhost:5000/prods/user_product', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${localStorage.getItem("token")}`
                },
                body: JSON.stringify(email),
            });
      
            if (!res.ok) {
              const data = await res.json();
              throw new Error(data.msg);
            }
      
            const data = await res.json();
            setPendingList(data);
          } catch (err) {
            setError(err.message);
          } finally {
            setIsLoading(false);
          }
        };
        fetchPendingList();
      }, []);


      const info = pendingList.map(item => {
        return {
          id: item._id,
          produit: item.produits,
          marque: item.marque,
          référence: item.référence,
          installation: item.annéeInstallation,        
          entretenu: item.entretenu,
          année: item.selectedYearEntretenu,
        }
      });


      
      const handleDeleteProduct = async (id) => {
        try {
            const email = localStorage.getItem("email");
            console.log('id', id)
    
            const res = await fetch('http://localhost:5000/prods/remove_product', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({ id, email })
            });
    
            if (!res.ok) {
                const data = await res.json();
                throw new Error(data.msg);
            }
    
            const data = await res.json();
            setPendingList(pendingList.filter(item => item.id !== id));
        } catch (err) {
            console.error(err);
            setError(err.message);
        }
    };
  
     return (
        <>
            <div className="mt-10 sm:mt-0 w-[92%] ml-12">
                <div className="md:grid md:grid-cols-2 md:gap-6">
                    <div className="mt-5 md:col-span-2 md:mt-0">               
                        <CRUDTable
                            data={info} 
                            link={`/user-projets-details/`} 
                            pencilIcon={<IoPencil style={{fontSize: '18px', cursor: 'pointer', color: 'green'}}/>}
                            eyeIcon={<IoEyeOutline style={{fontSize: '18px', cursor: 'pointer', color: '#f8c408'}}/>}
                            deleteIcon={<IoTrashOutline style={{fontSize: '18px', color: 'red', cursor: 'pointer'}} onClick={() => handleDeleteProduct(info.id)} />}              
                        />
                    </div>
                </div>
            </div>
        </>
    )
}

export default UserNewDevice

CodePudding user response:

The issue is that info is an array, not an object, and info.id is not a valid reference. To get the specific id of the item you want to delete, you need to pass it as a parameter when calling the handleDeleteProduct function from within the deleteIcon prop. You can modify the code as follows:

deleteIcon={(id) => <IoTrashOutline style={{fontSize: '18px', color: 'red', cursor: 'pointer'}} onClick={() => handleDeleteProduct(id)} />}

And when you call it in the map function:

const info = pendingList.map(item => {
  return {
    id: item._id,
    produit: item.produits,
    marque: item.marque,
    référence: item.référence,
    installation: item.annéeInstallation,        
    entretenu: item.entretenu,
    année: item.selectedYearEntretenu,
  }
});

Becomes:

const info = pendingList.map(item => {
  return {
    id: item._id,
    produit: item.produits,
    marque: item.marque,
    référence: item.référence,
    installation: item.annéeInstallation,        
    entretenu: item.entretenu,
    année: item.selectedYearEntretenu,
    deleteIcon: item._id,
  }
});
  • Related