diff --git a/packages/lexical-react/src/shared/useYjsCollaboration.tsx b/packages/lexical-react/src/shared/useYjsCollaboration.tsx index 371a6f4721f..a8f4e49da17 100644 --- a/packages/lexical-react/src/shared/useYjsCollaboration.tsx +++ b/packages/lexical-react/src/shared/useYjsCollaboration.tsx @@ -155,9 +155,18 @@ export function useYjsCollaboration( return () => { if (isReloadingDoc.current === false) { - Promise.resolve(connectionPromise).then(() => { + if (connectionPromise) { + connectionPromise.then(disconnect); + } else { + // Workaround for race condition in StrictMode. It's possible there + // is a different race for the above case where connect returns a + // promise, but we don't have an example of that in-repo. + // It's possible that there is a similar issue with + // TOGGLE_CONNECT_COMMAND below when the provider connect returns a + // promise. + // https://github.com/facebook/lexical/issues/6640 disconnect(); - }); + } } provider.off('sync', onSync); @@ -198,18 +207,16 @@ export function useYjsCollaboration( return editor.registerCommand( TOGGLE_CONNECT_COMMAND, (payload) => { - if (connect !== undefined && disconnect !== undefined) { - const shouldConnect = payload; - - if (shouldConnect) { - // eslint-disable-next-line no-console - console.log('Collaboration connected!'); - connect(); - } else { - // eslint-disable-next-line no-console - console.log('Collaboration disconnected!'); - disconnect(); - } + const shouldConnect = payload; + + if (shouldConnect) { + // eslint-disable-next-line no-console + console.log('Collaboration connected!'); + connect(); + } else { + // eslint-disable-next-line no-console + console.log('Collaboration disconnected!'); + disconnect(); } return true;