Skip to content
Advertisement

tried a lot but not able to make deletehandler function working. here is my code

This is my librarylist component in which i pass deletehandler function to delete the row from library management. I don’t know which part of the code is causing the problem. Any helps/suggestions are welcome. LibraryBookList.js

 const LibraryBookList = (props) => {
 const[database, setDatabase]=useState()
 const deleteHandler = (bookdataId) => {

 const newDatabase=[...database];

 const index= database.findIndex((bookdata)=>bookdata.id===bookdataId)

 newDatabase.splice(index,1)

setDatabase(newDatabase);
} ;

return (
<ul className={classes.list}>
  {props.database.map((bookdata) => 
     (<LibraryBook

      key={bookdata.key}
      id={bookdata.id}
      bookname={bookdata.bookName}
      author={bookdata.author}
      publisher={bookdata.publisher}
      pages={bookdata.pages}
      serialno={bookdata.serialNo}
      onSelect={deleteHandler}
    />
  ))}
</ul>
   )};

here i pass deletehandler via props LibraryBook.js

 const LibraryBook = (props) => {

 return (
  <li>
  <table className={classes.table}>
    <tbody>
      <tr className={classes.table_row}>
        <td className={classes.row_data}>{props.serialno}</td>
        <td className={classes.row_data}>{props.pages}</td>
        <td className={classes.row_data}>{props.bookname}</td>
        <td className={classes.row_data}>{props.author}</td>
        <td className={classes.row_data}>{props.publisher}</td>
        <td>
          <button className={classes.delete_btn} onClick={(props.onSelect(props.id))}>
            Delete
          </button>
        </td>
      </tr>
    </tbody>
  </table>
</li>
export default LibraryBookList;

**BookData.js **

 const BookData = (props) => {
 const [isLoading, setIsLoading] = useState(true);
 const [loadedLibrarydata, setLoadedLibrarydata] = useState();
 useEffect(() => {
 setIsLoading(true);
 fetch(
  "https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
  )
  .then((response) => {
    // console.log('response',response.json())
    return response.json();
  })
  .then((data) => {
    const database = [];
    console.log("data", data);
    for (const key in data) {
      const bookdata = {
        id: key,
        ...data[key],
      };
      database.push(bookdata);
    }
    setIsLoading(false);
    setLoadedLibrarydata(database);
  });
  }, []);

  if (isLoading) {
  return (
  <section>
    <p>Loading.....</p>
  </section>
);
}

return (
<section>
  <h1>Book Data Base</h1>
  <table className={classes.table}>
    <thead>
      <tr className={classes.table_row}>
        <th className={classes.row_heading}>Serial No</th>
        <th className={classes.row_heading}>Pages</th>
        <th className={classes.row_heading}>Book Name</th>
        <th className={classes.row_heading}>Author</th>
        <th className={classes.row_heading}>Publisher</th>
      </tr>
    </thead>
  </table>
  {loadedLibrarydata && loadedLibrarydata.length && (
    <LibraryBooklist database={loadedLibrarydata} />
   )}
 </section>
 );
 };
 export default BookData;

NewDataBase.js

 const NewDataBase = () => {
 const history=useHistory();

  const addDataHandler = (bookData) => {
   console.log('bookData',bookData);
   fetch(
    "https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json",
    {
    method: "POST",
    body: JSON.stringify(bookData),
    headers: {
      "Content-type": "application/json",
    },
   }
  ).then(()=>{
  history.replace('/')

   })
   };
  return (
 <section>
  <DataBaseForm onAddNewData={addDataHandler} />
 </section>
  );
   };
  export default NewDataBase;

Advertisement

Answer

The code has a few issues: 1) props.onSelect(props.id) inside onClick. Instead you should give a referance to that function. 2) You didn’t have anything in database state before you click delete button. That is why ... spread operator didn’t work 3) You are displaying props.database instead of database state. That is way the changes didn’t show up even after you deleted a bookdata. I also fixed some small issues. Now it is working perfectly:

// !! you can put all the code into one file and run for testing.
// !! I removed stylings as I didn't have the source
import {useState, useEffect} from 'react'

const LibraryBooklist = (props) => {
  const[database, setDatabase]=useState(props.database)
  const deleteHandler = (bookdataId) => {
    const newDatabase=database.filter((bookdata)=>bookdata.id!==bookdataId);
    setDatabase(newDatabase);
  }

  return (
  <ul>
  {database.map((bookdata) => 
      <LibraryBook
        key={bookdata.id}
        id={bookdata.id}
        bookname={bookdata.bookName}
        author={bookdata.author}
        publisher={bookdata.publisher}
        pages={bookdata.pages}
        serialno={bookdata.serialNo}
        onSelect={deleteHandler}
      />
  )}
  </ul>
)};


const LibraryBook = (props) => {
 const {id, onSelect} = props
 return (
  <li>
  <table>
    <tbody>
      <tr>
        <td>{props.serialno}</td>
        <td>{props.pages}</td>
        <td>{props.bookname}</td>
        <td>{props.author}</td>
        <td>{props.publisher}</td>
        <td>
          <button onClick={() => onSelect(id)}>
            Delete
          </button>
        </td>
      </tr>
    </tbody>
  </table>
</li>
)}

const BookData = (props) => {
  const [isLoading, setIsLoading] = useState(true);
  const [loadedLibrarydata, setLoadedLibrarydata] = useState();
  useEffect(() => {
    setIsLoading(true);
    fetch(
    "https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
    )
    .then((response) => {
      // console.log('response',response.json())
      return response.json();
    })
    .then((data) => {
      const database = [];
      
      for (const key in data) {
        const bookdata = {
          id: key,
          ...data[key],
        };
        database.push(bookdata);
      }
      setIsLoading(false);
      setLoadedLibrarydata(database);
    });
  }, []);

  if (isLoading) {
    return (
    <section>
      <p>Loading.....</p>
    </section>
    );
  }

  return (
  <section>
    <h1>Book Data Base</h1>
    <table>
      <thead>
        <tr>
          <th>Serial No</th>
          <th>Pages</th>
          <th>Book Name</th>
          <th>Author</th>
          <th>Publisher</th>
        </tr>
      </thead>
    </table>
    {loadedLibrarydata && loadedLibrarydata.length && (
      <LibraryBooklist database={loadedLibrarydata} />
    )}
  </section>
  );
};

export default BookData;
Advertisement