I'm working on a fairly simple React functional component that gets a value (tag
) from the URL and requests documents from firestore correspondig to that tag
(inlc. firestore query cursor to use with a load more button). The whole component consists of a function declaration and a useEffect
hook that calls this function.
Basically the component works fine. But there's a catch: ESLint tells me that I need to include the function as a dependency of the useEffect
hook:
React Hook useEffect has a missing dependency: 'getNextImages'. Either include it or remove the dependency array react-hooks/exhaustive-deps
If I include the function into the dependency array or remove the dependency array entirely, the component ends up in a infinite render loop, of course.
I could skip the dependency array for ESLint with // eslint-disable-next-line
, but that feels not right.
I tried to fix this by wrapping getNextImages
into a useCallback
hook without success. But maybe I've done it the wrong way. I never had to use useCallback
before…
Is there anybody able to tell me a hint?
You'll find my component at https://codesandbox.io/s/great-liskov-d12l3?file=/src/App.js. Or here:
import { useEffect, useState } from "react";
import firebase from "firebase";
import { useParams } from "react-router-dom";
const GalleryTag = () => {
//const [isPending, setIsPending] = useState(true);
//const [galleryData, setGalleryData] = useState([]);
//const [lastDocument, setLastDocument] = useState(null);
//const [isLastPage, setIsLastPage] = useState(false);
const numImagesPerPage = 20;
const { tag } = useParams();
const getNextImages = (lastDocument) => {
let query;
!lastDocument
? (query = firebase
.firestore()
.collectionGroup("images")
.where("showinapp", "==", true)
.where("tags", "array-contains", tag)
.orderBy("createdate", "desc")
.limit(numImagesPerPage)
.get())
: (query = firebase
.firestore()
.collectionGroup("images")
.where("showinapp", "==", true)
.where("tags", "array-contains", tag)
.orderBy("createdate", "desc")
.startAfter(lastDocument)
.limit(numImagesPerPage)
.get());
query
.then((data) => {
setIsLastPage(data.empty);
setIsPending(false);
setLastDocument(data.docs[data.docs.length - 1]);
setGalleryData((galleryData) => galleryData.concat(data.docs));
})
.catch((error) => console.error(error));
};
useEffect(() => {
getNextImages();
}, [tag]);
return <>JSX goes here then</>;
};
export default GalleryTag;