Search code examples
reactjsfirebasereact-component

React local element not updating?


I have a component which has a local variable

  let endOfDocument = false;

And I have a infinite scroll function in my useEffect

useEffect(() => {
const { current } = selectScroll;
current.addEventListener('scroll', () => {
  if (current.scrollTop + current.clientHeight >= current.scrollHeight) {
    getMoreExercises();
  }
});
return () => {
  //cleanup
  current.removeEventListener('scroll', () => {});
};
}, []);

In my getMoreExercises function I check if we reached the last document in firebase

function getMoreExercises() {
 if (!endOfDocument) {
  let ref = null;
  if (selectRef.current.value !== 'All') {
    ref = db
      .collection('exercises')
      .where('targetMuscle', '==', selectRef.current.value);
  } else {
    ref = db.collection('exercises');
  }
  ref
    .orderBy('average', 'desc')
    .startAfter(start)
    .limit(5)
    .get()
    .then((snapshots) => {
      start = snapshots.docs[snapshots.docs.length - 1];

      if (!start) endOfDocument = true; //Here

      snapshots.forEach((exercise) => {
        setExerciseList((prevArray) => [...prevArray, exercise.data()]);
      });
    });
}
}

And when I change the options to another category I handle it with a onChange method

  function handleCategory() {
    endOfDocument = false;
    getExercises();
  }

I do this so when we change categories the list will be reset and it will no longer be the end of the document. However the endOfDocument variable does not update and getMoreExercise function will always have the endOfDocument value of true once it is set to true. I cannot change it later. Any help would be greatly appreciated.


Solution

  • As @DevLoverUmar mentioned, that would updated properly, but since the endOfDocument is basically never used to "render" anything, but just a state that is used in an effect, I would put it into a useRef instead to reduce unnecessary rerenders.