Don't abuse useMemo for creating a MatrixClient

This commit is contained in:
Robin Townsend 2022-05-31 10:33:10 -04:00
parent 5b3183cbd3
commit 26251e1e60

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { useState, useEffect, useCallback, useMemo } from "react"; import { useState, useEffect, useCallback, useRef } from "react";
import matrix, { InteractiveAuth } from "matrix-js-sdk/src/browser-index"; import matrix, { InteractiveAuth } from "matrix-js-sdk/src/browser-index";
import { MatrixClient } from "matrix-js-sdk/src/client"; import { MatrixClient } from "matrix-js-sdk/src/client";
@ -35,16 +35,19 @@ export const useInteractiveRegistration = (): [
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string>(); const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string>();
const [recaptchaKey, setRecaptchaKey] = useState<string>(); const [recaptchaKey, setRecaptchaKey] = useState<string>();
const authClient = useMemo(() => matrix.createClient(defaultHomeserver), []); const authClient = useRef<MatrixClient>();
if (!authClient.current) {
authClient.current = matrix.createClient(defaultHomeserver);
}
useEffect(() => { useEffect(() => {
authClient.registerRequest({}).catch((error) => { authClient.current.registerRequest({}).catch((error) => {
setPrivacyPolicyUrl( setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url
); );
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key); setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
}); });
}, [authClient]); }, []);
const register = useCallback( const register = useCallback(
async ( async (
@ -55,9 +58,9 @@ export const useInteractiveRegistration = (): [
passwordlessUser?: boolean passwordlessUser?: boolean
): Promise<[MatrixClient, Session]> => { ): Promise<[MatrixClient, Session]> => {
const interactiveAuth = new InteractiveAuth({ const interactiveAuth = new InteractiveAuth({
matrixClient: authClient, matrixClient: authClient.current,
doRequest: (auth) => doRequest: (auth) =>
authClient.registerRequest({ authClient.current.registerRequest({
username, username,
password, password,
auth: auth || undefined, auth: auth || undefined,
@ -111,7 +114,7 @@ export const useInteractiveRegistration = (): [
return [client, session]; return [client, session];
}, },
[authClient] []
); );
return [privacyPolicyUrl, recaptchaKey, register]; return [privacyPolicyUrl, recaptchaKey, register];