How to fetch data from client side components in Next.js with app router?
I have this method for fetching data:
import { useState } from "react";
import { get, limitToFirst, orderByKey, query, ref, startAfter } from "firebase/database";
import { db } from "@/lib/firebase";
import { Product } from "@/types/product";
const useFetchProducts = (initialProducts: Product[]) => {
const [products, setProducts] = useState(initialProducts);
const [loading, setLoading] = useState(false);
const fetchMoreProducts = async (startKey: string | null) => {
setLoading(true);
try {
const productsRef = ref(db, 'products');
let productsQuery = query(productsRef, orderByKey(), limitToFirst(20));
if (startKey) {
productsQuery = query(productsRef, orderByKey(), startAfter(startKey), limitToFirst(20));
}
console.log("Test 1");
const snapshot = await get(productsQuery);
console.log("Test 2");
if (snapshot.exists()) {
const productsData = snapshot.val();
const productsArray: Product[] = Object.keys(productsData).map(key => ({
id: Number(key),
...productsData[key],
}));
setProducts((prevProducts) => [...prevProducts, ...productsArray]);
}
} catch (error) {
console.error('Error fetching products:', error);
} finally {
setLoading(false);
}
};
return { products, loading, fetchMoreProducts };
};
export default useFetchProducts;
Using this method in server-side component works well and products are fetched. if I call this from client-side component then it stops at line:
const snapshot = await get(productsQuery);
Does anybody know how can I fix this problem?
I tried to pass method from server side component to client side but it is not allowed. Also I tried to have this in useEffect in client side.