I am working on a React Native project that uses Firestore to fetch a list of services. I am trying to fetch services with a price greater than or equal to 70 and implement pagination using Firestore’s startAfter method. However, I am encountering an error when fetching more data.
import React, { useState, useEffect } from 'react';
import firestore from '@react-native-firebase/firestore';
import { FlashList } from "@shopify/flash-list";
const PAGE_SIZE = 10;
const MyComponent = () => {
const [services, setServices] = useState([]);
const [loading, setLoading] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [lastVisible, setLastVisible] = useState(null);
useEffect(() => {
fetchServices(true);
}, []);
const fetchServices = async (initial = false) => {
if (!initial && (loadingMore || !lastVisible)) return;
initial ? setLoading(true) : setLoadingMore(true);
try {
let query = firestore().collection("services").where("price", ">=", 70);
if (!initial && lastVisible) {
query = query.startAfter(lastVisible);
}
query = query.limit(PAGE_SIZE);
const servicesCollection = await query.get();
const servicesList = servicesCollection.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setServices((prevServices) =>
initial ? servicesList : [...prevServices, ...servicesList]
);
setLastVisible(
servicesCollection.docs[servicesCollection.docs.length - 1]
);
console.log(servicesCollection.docs[servicesCollection.docs.length - 1]);
} catch (error) {
console.error("Error fetching services: ", error);
} finally {
initial ? setLoading(false) : setLoadingMore(false);
}
};
return (
<FlashList
data={services}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
estimatedItemSize={200}
showsVerticalScrollIndicator={false}
onEndReached={() => fetchServices(false)}
onEndReachedThreshold={0.5}
ListFooterComponent={<RenderLoading />}
/>
);
};
Error fetching services: [Error: [firestore/invalid-argument] Client
specified an invalid argument. Note that this differs from
failed-precondition. invalid-argument indicates arguments that are
problematic regardless of the state of the system (e.g., an invalid
field name).]
- The initial fetch works correctly, but when fetchServices(false) in FlashList is
called, the error occurs. - I have two documents with a price field in my Firestore
collection. - Removing the .where(“price”, “>=”, 70) clause eliminates the error
but returns all documents instead of filtering by price.
What I’ve Tried:
-
Verified that the price field exists in all documents and is a valid
number. -
Checked the Firestore rules and indexes.
Any help in resolving this issue would be greatly appreciated. Thank you!