Implemeting search funcionality on iterated data from an API

So I created a sandbox of the thing I am working on https://codesandbox.io/s/charming-hellman-h9yqg Basically here I am fetching data from an API, I have iterated the data in Book Component, I have also Link in component/HoverBooks which is taking me to the details page/Book. I have iterated the data in the Search Component. I am trying to implement Search functionality of bookNames, which when they pressed are pushing me to the DetailsPage/Book. If something is wrong with sandbox please leave a comment. Thanks

Answer

I saw a bit of trouble in the way you prepare the data for your filter function. The key piece of code is

function filterBooks(book) {
    console.log(book);
    if (!searchValue.length) return true;
    return book.bookName?.toLowerCase().includes(searchValue.toLowerCase());
  }
  return (
    <div>
      {Object.keys(data)
        .map((key) => data[key])
        .reduce((acc, curr) => acc.concat(curr), [])
        .filter(filterBooks)
        .map((book) => {
          return (
            <>
              <div
                onClick={() => {
                  history.push("/book/id", { book });
                }}
              >
                {" "}
                {book.bookName}{" "}
              </div>
            </>
          );
        })}

https://codesandbox.io/s/affectionate-pine-pbchq?file=/src/Book.js

Fixed!

Leave a Reply

Your email address will not be published. Required fields are marked *