Home > Enterprise >  map is not function error, when get data from Firebase
map is not function error, when get data from Firebase

Time:06-18

I get data from firebase firestore. It returns "filter is not function and error". I think it is problem because firstly runs LoadBooks function and after brings data from firestore. How can i fix it? Async? I can't write it rightly or i dont know, just can't do, need a help please.

*here isnt error if i fetch same data from JSON file.

**// Fetch Book to Home Page List**

  const [list, setList] = useState();

  useEffect(() => {
      const data = onSnapshot(collection(db, "Books"), (snapshot) => {
        setList(snapshot.docs.map((doc) => doc.data()));
      });
      return data;
  }, []);

**//search**
  const [search, setSearch] = useState("");
  **//Category filter**
  const [filter, setFilter] = useState("all");

  function LoadBooks() {
    // search
    const book = list.filter((val) => {
      if (search === "") {
        return val;
      } else if (val.title.toLowerCase().includes(search.toLowerCase())) {
        return val;
      }
    })
      // filter and map
      .map((item) => {
        if (item.category === filter) {
          return (
            <Book key={item.id} {...item} />
          );
        } else if (filter === "all") {
          return (
            <Book key={item.id} {...item} />
          );
        }
      })
    return book;
  }

  const book = LoadBooks();

CodePudding user response:

Whether you like it or not, an operation where you fetch data from an external server or service will be asynchronous. What I suspect is happening here is that you are making your call to firebase, gets a promise from javascript which you aren't waiting for to resolve and then you perform a .map on an unresolved Promise.

I highly recommend you to look up async await and Promises :)

CodePudding user response:

Your LoadBooks function depends on the list state, so needs to be executed in a useEffect handler and declare that dependency. Something like this:

useEffect(() => {
  if (list != null) {
    const book = LoadBooks();
  }
}, [list]);
  • Related