Files
ThreadNet-Web/src/hooks/useAccountData.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

57 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-06-25 16:45:01 +01:00
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-06-29 13:11:58 +01:00
import { useCallback, useState } from "react";
2023-08-30 18:55:02 +01:00
import { ClientEvent, MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";
2020-06-25 16:45:01 +01:00
import { useTypedEventEmitter } from "./useEventEmitter";
2020-06-25 16:45:01 +01:00
const tryGetContent = <T extends {}>(ev?: MatrixEvent): T | undefined => ev?.getContent<T>();
2020-06-25 16:45:01 +01:00
// Hook to simplify listening to Matrix account data
export const useAccountData = <T extends {}>(cli: MatrixClient, eventType: string): T => {
const [value, setValue] = useState<T | undefined>(() => tryGetContent<T>(cli.getAccountData(eventType)));
2020-06-25 16:45:01 +01:00
const handler = useCallback(
(event) => {
if (event.getType() !== eventType) return;
setValue(event.getContent());
2020-07-20 20:43:49 +01:00
},
[eventType],
);
useTypedEventEmitter(cli, ClientEvent.AccountData, handler);
2020-06-25 16:45:01 +01:00
2020-06-25 16:55:38 +01:00
return value || ({} as T);
2020-06-25 16:45:01 +01:00
};
2023-08-30 18:55:02 +01:00
// Currently not used, commenting out otherwise the dead code CI is unhappy.
// But this code is valid and probably will be needed.
2020-06-25 16:45:01 +01:00
2023-08-30 18:55:02 +01:00
// export const useRoomAccountData = <T extends {}>(room: Room, eventType: string): T => {
// const [value, setValue] = useState<T | undefined>(() => tryGetContent<T>(room.getAccountData(eventType)));
2020-06-25 16:45:01 +01:00
2023-08-30 18:55:02 +01:00
// const handler = useCallback(
// (event) => {
// if (event.getType() !== eventType) return;
// setValue(event.getContent());
// },
// [eventType],
// );
// useTypedEventEmitter(room, RoomEvent.AccountData, handler);
// return value || ({} as T);
// };