47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
|
|
import { useEffect, useState } from 'react';
|
||
|
|
import { Method } from 'matrix-js-sdk';
|
||
|
|
import { useMatrixClient } from './useMatrixClient';
|
||
|
|
|
||
|
|
export type ExtendedProfile = {
|
||
|
|
pronouns?: string;
|
||
|
|
timezone?: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
export const useExtendedProfile = (userId: string): ExtendedProfile => {
|
||
|
|
const mx = useMatrixClient();
|
||
|
|
const [extProfile, setExtProfile] = useState<ExtendedProfile>({});
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
let cancelled = false;
|
||
|
|
|
||
|
|
const fetchField = async <T extends Record<string, string>>(
|
||
|
|
field: string,
|
||
|
|
): Promise<string | undefined> => {
|
||
|
|
try {
|
||
|
|
const res = await mx.http.authedRequest<T>(
|
||
|
|
Method.Get,
|
||
|
|
`/profile/${encodeURIComponent(userId)}/${field}`,
|
||
|
|
);
|
||
|
|
return res[field as keyof T] as string | undefined;
|
||
|
|
} catch {
|
||
|
|
return undefined;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
Promise.all([
|
||
|
|
fetchField<{ 'm.pronouns': string }>('m.pronouns'),
|
||
|
|
fetchField<{ 'm.tz': string }>('m.tz'),
|
||
|
|
]).then(([pronouns, timezone]) => {
|
||
|
|
if (!cancelled) {
|
||
|
|
setExtProfile({ pronouns: pronouns || undefined, timezone: timezone || undefined });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
return () => {
|
||
|
|
cancelled = true;
|
||
|
|
};
|
||
|
|
}, [mx, userId]);
|
||
|
|
|
||
|
|
return extProfile;
|
||
|
|
};
|