Home > Blockchain >  Delete doc Firebase v9 React v18, indexOf issue
Delete doc Firebase v9 React v18, indexOf issue

Time:07-13

//Delete document
const deleteAnime = (e) => {
  e.preventDefault()
  deleteDoc(doc(db,"Users", uid,"anime",anime.id))
  
}

This is the code to delete the document, where anime.id is document id

{anime.map(function(d, idx){
 return (<form onSubmit={deleteAnime} className={styles.card}>
        <h2 key={idx}>{idx 1}. {d.title}</h2>
          <p key={idx}>Genre: {d.genre}</p>
          <p key={idx}>Number of episodes: {d.numb}</p>
          <p key={idx}>Comment: {d.comment}</p>
          <p key={idx}>Rating: {d.rating}/10</p>
           <button key={idx} onClick={(e) => {deleteAnime(e, index)}}>Remove</button>
        </form>)})}

This is the return code where I attempted both in div and in form, and receiving the error that:

Cannot read properties of undefined (reading 'indexOf')

CodePudding user response:

The mistake is you are trying to access id from anime but it's an array not an object so i would suggest get the index of the clicked item and there will be no need to use form at all if you are not submitting any details from input.

Also you don't need to define key it will be only on the root element of the map function

const deleteAnime = (item) => {
    e.preventDefault()
    deleteDoc(doc(db, "Users", uid, "anime", item.id));
}

{
    anime.map((d, idx) => {
        return (
            <div key={idx} className={styles.card}>
                <h2>{idx 1}. {d.title}</h2>
                <p>Genre: {d.genre}</p>
                <p>Number of episodes: {d.numb}</p>
                <p>Comment: {d.comment}</p>
                <p>Rating: {d.rating}/10</p>
                <button key={idx} onClick={() => deleteAnime(d)}>Remove</button>
            </div>
        )
    })
}
  • Related