3

First of all, I use Firebase to structure my DB.

I saved my db value through useState like this way.

const getFromFirestore = useCallback(() => {
    console.log("GET From Firestore");
    webtoonSites.forEach((siteName) => {
      days.forEach(async (day) => {
        await dbService
          .collection(userObj.uid)
          .doc(siteName)
          .collection(day)
          .onSnapshot((snapShot) => {
            const webtoonArr = snapShot.docs.map((doc) => doc.data());
            setMyWebtoons((prev) => {
              return {
                ...prev,
                [siteName]: {
                  ...prev[siteName],
                  [day]: webtoonArr,
                },
              };
            });
          });
      });
    });
    setDataInit(true);
  }, [myWebtoons, userObj]);

And then, I changed the DB value through Firebase because there was something to be deleted.

if (ok) {
        console.log("delete");
      await dbService
        .collection(userObj.uid)
        .doc(siteName)
        .collection(targetWebtoonObj.day)
        .doc(targetWebtoonObj.title)
        .delete();
    }

I thought that React would not have recognized that the DB value was changed, but it recognized it and took an automatic re-rendering process.

So I checked the execution of the function 'getFromFirestore' with console.log() that function sets the state value from the db , but it was not even executed.

When and how did React hooks recognized the db-changed and changed the state value...?

skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

3

According to the Firestore documentation on listening for changes (emphasis mine):

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

So each time the data changes, your onSnapshot callback gets called again. And since you process the data in there again, and call setMyWebtoons again, the updated data is automatically rerendered. Pretty cool, right? :)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807