From 5b88924e82b2b402ee08acc8dc4e3fd4053f8a73 Mon Sep 17 00:00:00 2001 From: Ajay Bura <32841439+ajbura@users.noreply.github.com> Date: Sun, 8 Dec 2024 20:34:23 +0530 Subject: [PATCH] use react-query in room event hook --- src/app/hooks/useRoomEvent.ts | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/app/hooks/useRoomEvent.ts b/src/app/hooks/useRoomEvent.ts index e7a9e3739..b01a89f71 100644 --- a/src/app/hooks/useRoomEvent.ts +++ b/src/app/hooks/useRoomEvent.ts @@ -1,9 +1,9 @@ import { MatrixEvent, Room } from 'matrix-js-sdk'; -import { useCallback, useEffect } from 'react'; +import { useCallback, useMemo } from 'react'; import to from 'await-to-js'; import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend'; +import { useQuery } from '@tanstack/react-query'; import { useMatrixClient } from './useMatrixClient'; -import { AsyncStatus, useAsyncCallback } from './useAsyncCallback'; const useFetchEvent = (room: Room, eventId: string) => { const mx = useMatrixClient(); @@ -19,7 +19,7 @@ const useFetchEvent = (room: Room, eventId: string) => { return mEvent; }, [mx, room.roomId, eventId]); - return useAsyncCallback(fetchEventCallback); + return fetchEventCallback; }; /** @@ -29,22 +29,19 @@ const useFetchEvent = (room: Room, eventId: string) => { * @returns `MatrixEvent`, `undefined` means loading, `null` means failure */ export const useRoomEvent = (room: Room, eventId: string) => { - const event = room.findEventById(eventId); + const event = useMemo(() => room.findEventById(eventId), [room, eventId]); - const [fetchState, fetchEvent] = useFetchEvent(room, eventId); + const fetchEvent = useFetchEvent(room, eventId); - useEffect(() => { - if (!event) { - fetchEvent(); - } - }, [event, fetchEvent]); + const { data, error } = useQuery({ + enabled: event === undefined, + queryKey: [room.roomId, eventId], + queryFn: fetchEvent, + }); if (event) return event; + if (data) return data; + if (error) return null; - if (fetchState.status === AsyncStatus.Idle || fetchState.status === AsyncStatus.Loading) - return undefined; - - if (fetchState.status === AsyncStatus.Success) return fetchState.data; - - return null; + return undefined; };