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

Commit

Permalink
Unregister favourite listeners automatically
Browse files Browse the repository at this point in the history
  • Loading branch information
andybalaam committed Jan 5, 2023
1 parent 7d83234 commit d6f3607
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/hooks/useFavouriteMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { IContent, MatrixEvent } from "matrix-js-sdk/src/models/event";
import { useCallback } from "react";
import { useCallback, useEffect, useRef } from "react";

export interface FavouriteStorage {
eventId: string;
Expand Down Expand Up @@ -63,6 +63,8 @@ export default function useFavouriteMessages() {
ioElementFavouriteMessages = loadFavourites();
}

const myListeners = useRef<(() => void)[]>([]);

const isFavourite = (eventId: string): boolean => {
return ioElementFavouriteMessages.some((f) => f.eventId === eventId);
};
Expand Down Expand Up @@ -96,20 +98,26 @@ export default function useFavouriteMessages() {
return JSON.parse(JSON.stringify(ioElementFavouriteMessages));
}, []);

function registerFavouritesChangedListener(listener: () => void) {
favouritesChangedListeners.push(listener);
}

function unregisterFavouritesChangedListener(listener: () => void) {
favouritesChangedListeners = favouritesChangedListeners.filter((l) => l !== listener);
}
const registerFavouritesChangedListener = useCallback(
(listener: () => void) => {
favouritesChangedListeners.push(listener);
myListeners.current.push(listener);
},
[myListeners],
);

useEffect(() => {
const myLists = myListeners.current;
return () => {
favouritesChangedListeners = favouritesChangedListeners.filter((l) => !myLists.find(l));
};
}, []);

return {
getFavouriteMessages,
isFavourite,
toggleFavourite,
clearFavouriteMessages,
registerFavouritesChangedListener,
unregisterFavouritesChangedListener,
};
}

0 comments on commit d6f3607

Please sign in to comment.