From f1c050c3273b1da4c98e20196117e6e12fc0d0b3 Mon Sep 17 00:00:00 2001 From: Robin Townsend Date: Wed, 2 Nov 2022 11:23:05 -0400 Subject: [PATCH] Don't doubly initialize the client in strict mode --- src/ClientContext.tsx | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/ClientContext.tsx b/src/ClientContext.tsx index e5109b6..8f81c85 100644 --- a/src/ClientContext.tsx +++ b/src/ClientContext.tsx @@ -22,6 +22,7 @@ import React, { createContext, useMemo, useContext, + useRef, } from "react"; import { useHistory } from "react-router-dom"; import { MatrixClient, ClientEvent } from "matrix-js-sdk/src/client"; @@ -87,6 +88,7 @@ interface Props { export const ClientProvider: FC = ({ children }) => { const history = useHistory(); + const initializing = useRef(false); const [ { loading, isAuthenticated, isPasswordlessUser, client, userName, error }, setState, @@ -100,6 +102,12 @@ export const ClientProvider: FC = ({ children }) => { }); useEffect(() => { + // In case the component is mounted, unmounted, and remounted quickly (as + // React does in strict mode), we need to make sure not to doubly initialize + // the client + if (initializing.current) return; + initializing.current = true; + const init = async (): Promise< Pick > => { @@ -190,7 +198,8 @@ export const ClientProvider: FC = ({ children }) => { userName: null, error: undefined, }); - }); + }) + .finally(() => (initializing.current = false)); }, []); const changePassword = useCallback(