Skip to content

setDoc fails to resolve after page refresh #9038

Open
@builtbyjavi

Description

@builtbyjavi

Operating System

Windows 11

Environment (if applicable)

node: 22, next: 12.3.4

Firebase SDK Version

11.7.1

Firebase SDK Product(s)

Firestore

Project Tooling

React / Typescript

Detailed Problem Description

I am trying to set data in Firestore based on a unique identifier in the url. I have a React hook that listens to Next.js Router.events and calls an update callback function on routeChangeComplete. When I navigate through my app, the related data I need is correctly added to Firestore; however, when I refresh the page the setDoc function hangs (i.e. the following line is never executed). I currently have a hacky workaround by introducing a small timeout around setDoc and I am really not sure why this works? Emphasis on this only happening when I refresh the page.

Steps and code to reproduce issue

useEffect(() => {
    syncData(window.location.href);

    Router.events.on('routeChangeComplete', syncData);

    return () => {
      Router.events.off('routeChangeComplete', syncData);
    };
}, []);


//NOT-WORKING (but should)
const syncData = useCallback(
    async (data) => {
        if (!documentReference) {
          return;
        }

       const firebaseFirestoreModule = await import('firebase/firestore');

        const { setDoc } = firebaseFirestoreModule;

        // we make it to here with the correct data
        await setDoc(documentReference, data, { merge: true });
        
        console.log('This is never reached and firestore document is never written to.');
    },
    [documentReference],
 );

//WORKING (but ugly)
const syncData= useCallback(
   async (data) => {
      return new Promise<void>((resolve) => {
        if (!documentReference) {
          resolve();
          return;
        }

       const firebaseFirestoreModule = await import('firebase/firestore');

        const { setDoc } = firebaseFirestoreModule;

        setTimeout(async () => {
          await setDoc(documentReference, data, { merge: true });
          resolve();
        }, 25);
      });
    },
    [documentReference],
  );

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions