Home > Blockchain >  Fetch data from firebase and initialise it in the useState before its mounted
Fetch data from firebase and initialise it in the useState before its mounted

Time:12-01

I am a beginner in react trying to fetch an object from firebase and I would like to initialise the useState with the data fetched from the database,but each time the data renders undefined value.Here is my truncated code

const ProductDetails = () => {
  const [tab, setTab] = useState("desc");
  const [products, setProducts] = useState([]);
  const reviewUser = useRef("");
  const reviewMsg = useRef("");
  const dispatch = useDispatch();
  const [rating, setRating] = useState(null);
  const { id } = useParams();
  const product = products.find(
    async (item) => (await item.key.slice(1)) === id
  );

const {
    image: imgUrl,
    title: productName,
    amount: price,
    description,
    shortDesc,
    category,
  } = product.data;

const fetchProducts = async () => {
    const db = getDatabase();
    const thumbnailRef = ref(db, "Contents/");

    onValue(thumbnailRef, (snapshot) => {
      snapshot.forEach((childSnapshot) => {
        const childData = childSnapshot.val();
        const childKey = childSnapshot.key;
        setProducts((prev) => [...prev, { key: childKey, data: childData }]);
      });
    });
  };

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

the error I get is "cannot read properties of undefined (reading 'data')".As I said I am a beginner to react and it could be I am making an amateur mistake,

CodePudding user response:

There should not be async await in product function

CodePudding user response:

First, you don't have to use async/ await inside the find. Also wrap it around useMemo to execute only when products change.

  const product = useMemo(() => products.find(
     (item) =>  item.key === id
  ), [products]);

secondly, product value could be ended up with undefined values. so needs to handle that.

const {
    image: imgUrl,
    title: productName,
    amount: price,
    description,
    shortDesc,
    category,
  } = product?.data ||  { image: '',title: '',amount: '',description: '',shortDesc: '',category: '',};
  • Related