From 0ee713a9f6e3cecb544613ffbdad0fe73e1516e8 Mon Sep 17 00:00:00 2001 From: Florian Duros Date: Wed, 13 Nov 2024 10:02:05 +0100 Subject: [PATCH] Use `useRoomState` & `useAsyncMemo` --- src/hooks/useIsEncrypted.ts | 40 +++++++++++++++---------------------- 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/src/hooks/useIsEncrypted.ts b/src/hooks/useIsEncrypted.ts index 33993f8ae8e..c9d3ed3bc80 100644 --- a/src/hooks/useIsEncrypted.ts +++ b/src/hooks/useIsEncrypted.ts @@ -6,33 +6,25 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only Please see LICENSE files in the repository root for full details. */ -import { useCallback, useEffect, useState } from "react"; -import { MatrixClient, MatrixEvent, Room, RoomStateEvent, EventType } from "matrix-js-sdk/src/matrix"; +import { MatrixClient, MatrixEvent, Room, EventType } from "matrix-js-sdk/src/matrix"; -import { useTypedEventEmitter } from "./useEventEmitter"; +import { useRoomState } from "./useRoomState.ts"; +import { useAsyncMemo } from "./useAsyncMemo.ts"; -// Hook to simplify watching whether a Matrix room is encrypted, returns undefined if room is undefined, return null when isRoomEncrypted is computed -export function useIsEncrypted(cli: MatrixClient, room?: Room): boolean | undefined | null { - const [isEncrypted, setIsEncrypted] = useState(null); +// Hook to simplify watching whether a Matrix room is encrypted, returns null if room is undefined or the state is loading +export function useIsEncrypted(cli: MatrixClient, room?: Room): boolean | null { + const encryptionStateEvent: MatrixEvent | undefined = useRoomState( + room, + (roomState) => roomState.getStateEvents(EventType.RoomEncryption)?.[0], + ); + return useAsyncMemo( + async () => { + const crypto = cli.getCrypto(); + if (!room || !crypto) return null; - useEffect(() => { - const func = async (): Promise => - room && setIsEncrypted(await cli.getCrypto()?.isEncryptionEnabledInRoom(room.roomId)); - func(); - }, [cli, room]); - const update = useCallback( - async (event: MatrixEvent) => { - if (room && event.getType() === EventType.RoomEncryption) { - try { - setIsEncrypted(await cli.getCrypto()?.isEncryptionEnabledInRoom(room.roomId)); - } catch { - setIsEncrypted(false); - } - } + return crypto.isEncryptionEnabledInRoom(room.roomId); }, - [cli, room], + [room, encryptionStateEvent], + null, ); - useTypedEventEmitter(room?.currentState, RoomStateEvent.Events, update); - - return isEncrypted; }