[SOLVED] How to delete a particular object using id

Hey, I tried to delete an object using this way

 const removeData = async(obj) => {
 const query = new Moralis.Query('contactFormModal')
 query.equalTo('objectId', obj.id )
const object = await query.first()
 if(object) {
   object.destroy({useMasterKey: true}).then(() => {
alert("Deleted Successfully!");
  }, (error) => {
     console.log(error);
   })
 }
  }

So If I have 3 records in my table then I am only able to delete the first one not the others so anyone can tell me how I can delete a particular object onClick of the delete button?
Thank you :slight_smile:

Can you post the rest of your code e.g. table and buttons.

You just need to pass in the correct objectId to removeData, and you could use a delete button beside each record.

Yes sure, here it is

const Home = () => {
  const { Moralis } = useMoralis();
  const { data } = useMoralisQuery("contactFormModal");
  const removeData = async(obj) => {
    const query = new Moralis.Query('contactFormModal')
    query.equalTo('objectId', obj.id )
   const object = await query.first()
    if(object) {
      object.destroy({useMasterKey: true}).then(() => {
   alert("Deleted Successfully!");
     }, (error) => {
        console.log(error);
      })
    }
     }

  return (
<div style={{ marginTop:"100px"}}>

   <table style={{
     margin:'auto',
     paddingTop:'80px',
   }}
   className='styledTable'>
     <thead>
       <tr>
       <th>No.</th>
       <th >Name</th>
       <th>Email</th>
       <th>Contact</th>
       <th>Action</th>
       </tr>
     </thead>
     <tbody>
        
         
     {data.map((obj, index) => {
        return (
          <tr key = {obj.id}>
            <th scope="row">{index + 1}</th>
            <td>{ obj.attributes.name}</td>
            <td>{ obj.attributes.email}</td>
            <td>{ obj.attributes.contact}</td>
           <td>
           <Link to={`/update/${obj.id}`}>
            <button className='btn btnEdit'>Edit</button>
            </Link>

               <button className='btn btnDelete' onClick={removeData}>Delete</button>
           </td>
          </tr>
        )
        })}
     </tbody>
   </table>

 </div>  )
}

does this return the expected object?

Nope, showing undefined in the console.

that could be the reason of not working, you can also try to use master key in that .first() in case that it matters

Okay, will give it a try. Thank you.

Solved it using the below code:-

let removeData;
  data.map((obj)=>{

   removeData = async() => {

  const query = new Moralis.Query('contactFormModal')
  query.equalTo('objectId',obj.id)
 const object = await query.first(({useMasterKey: true}))
  if(object) {
    object.destroy().then(() => {
 alert("Deleted Successfully!");
   }, (error) => {
      console.log(error);
    })
  }
     }
    })
1 Like