简体   繁体   中英

Firebase pagination problem, how to set the latest document reference correctly?

I am trying to perform infinite scroll in react component, but after all the data loads latestMealDoc becomes undefined.

Also same thing happens when I go to different route and come back to the component, the latest document is incorrect and I start getting the same items all over again.

Am i setting the state wrong?

const [latestMealDoc, setLatestMealDoc] = useContext(latestMealDocContext);

const getNextMeals = async () => {
  const ref = db
    .collection("meals")
    .orderBy("timestamp")
    .limit(6)
    .startAfter(latestMealDoc || 0);
  const data = await ref.get();
  data.docs.forEach((doc) => {
    const meal = doc.data();
    setMealSearchResults((prev: any) => [...prev, meal]);
  });
  setLatestMealDoc(data.docs[data.docs.length - 1]);
};
useEffect(() => {
  getNextMeals();
}, []);
  • Can you log the output of latestMealDoc ?
  • What are you expecting to see for latestMealDoc ?

It sounds like the undefined variable has not been assigned a value yet.

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM