1

i am creating a custom hook useFetchCollection that fetches data collection from firebase storage and displays it in the viewProduct.jsx, so the issue is that whenever i set the state of useFetchCollection in my viewPRoduct it gives me an error, so i'm unable to fetch data from firebase storage

"caught TypeError: useFetchCollection is not a function or its return value is not iterable at ViewProducts (ViewProducts.jsx:31:32) "

so here is my useFetchCollection.js file

import { collection, onSnapshot, orderBy, query } from "firebase/firestore";

import { useEffect, useState } from "react"; import { toast } from "react-toastify"; import { db } from "../pages/firebase/config";

const useFetchCollection = (collectionName) => { const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(false);

const getCollection = () => { setIsLoading(true); try { const docRef = collection(db, collectionName); const q = query(docRef, orderBy("createdAt", "desc")); onSnapshot(q, (snapshot) => { console.log(snapshot.docs); const allData = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), })); console.log(allData); setData(allData); setIsLoading(false); }); } catch (error) { setIsLoading(false); toast.error(error.message); } };

useEffect(() => { getCollection(); }, []);

return { data, isLoading }; };

export default useFetchCollection;

in this file i am getting the collection from firebase storage by creating a reference and setting it by an order and then listening to any changes by onSnapshot and then assigning data variable to changing data from firebase and then call the function getCollection in sideEffect

=>This is my viewProducts.jsx file

import React, { useEffect, useState } from "react";

import useFetchCollection from "../../customHooks/useFetchCollection"; 
const [data, setIsLoading] = useFetchCollection("product");// here i am getting an error 
Cable-Nerd
  • 43
  • 5

1 Answers1

1

Try the line of code below:

const { data, isLoading } = useFetchCollection("product");
Hoang Long
  • 446
  • 4
  • 5
  • hey thank you it's now atleast displaying the page and not giving that error, so what i come to know is that either const { setData, setIsLoading } = useFetchCollection("product"); or const { data, isLoading } = useFetchCollection("product"); is correct – Cable-Nerd May 05 '23 at 13:09
  • it still hasn't solved my problem, still giving me the same error @Hoang Long – Cable-Nerd May 21 '23 at 04:14