Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Update member count on room summary update #11488

Merged
merged 6 commits into from
Aug 31, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions src/hooks/useRoomMembers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { useCallback, useState } from "react";
import { useCallback, useMemo, useState } from "react";
import { Room, RoomEvent, RoomMember, RoomStateEvent } from "matrix-js-sdk/src/matrix";
import { throttle } from "lodash";

Expand Down Expand Up @@ -44,27 +44,40 @@ type RoomMemberCountOpts = {
throttleWait?: number;
};

// Hook to simplify watching Matrix Room joined member count
/**
* Returns a count of members in a given room
* @param room the room to track.
* @param opts The options.
* @returns the room member count.
*/
export const useRoomMemberCount = (room: Room, opts: RoomMemberCountOpts = { throttleWait: 250 }): number => {
const [count, setCount] = useState<number>(room.getJoinedMemberCount());

const { throttleWait } = opts;

const onMembershipUpdate = useCallback(() => {
const updateMembershipCount = useCallback((): void => {
setCount(room.getJoinedMemberCount());
}, [room]);

useTypedEventEmitter(
room.currentState,
RoomStateEvent.Members,
throttle(onMembershipUpdate, throttleWait, { leading: true, trailing: true }),
const throttledUpdate = useMemo(
() =>
throttle(
() => {
updateMembershipCount();
},
throttleWait,
{ leading: true, trailing: true },
),
[throttleWait, updateMembershipCount],
);
germain-gg marked this conversation as resolved.
Show resolved Hide resolved

useTypedEventEmitter(
room,
RoomEvent.Summary,
throttle(onMembershipUpdate, throttleWait, { leading: true, trailing: true }),
);
useTypedEventEmitter(room.currentState, RoomStateEvent.Members, throttledUpdate);

/**
* `room.getJoinedMemberCount()` caches the member count behind the room summary
* So we need to re-compute the member count when the summary gets updated
*/
useTypedEventEmitter(room, RoomEvent.Summary, throttledUpdate);
return count;
};

Expand Down
Loading