added useChannelMetadata and support kind 41

This commit is contained in:
Ren Amamiya
2023-04-19 09:33:46 +07:00
parent 697caca77b
commit b84c0ff0d6
3 changed files with 65 additions and 5 deletions

View File

@@ -0,0 +1,52 @@
import { RelayContext } from '@components/relaysProvider';
import { updateChannelMetadata } from '@utils/storage';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
export const useChannelMetadata = (id: string, fallback: string) => {
const [pool, relays]: any = useContext(RelayContext);
const [metadata, setMetadata] = useState(null);
const unsubscribe = useRef(null);
const fetchMetadata = useCallback(() => {
unsubscribe.current = pool.subscribe(
[
{
kinds: [41],
'#e': [id],
},
],
relays,
(event: { content: string }) => {
const json = JSON.parse(event.content);
// update state
setMetadata(json);
// update metadata in database
updateChannelMetadata(id, event.content);
},
undefined,
undefined,
{
unsubscribeOnEose: true,
logAllEvents: false,
}
);
}, []);
useEffect(() => {
const json = JSON.parse(fallback);
setMetadata(json);
// fetch kind 41
fetchMetadata();
return () => {
if (unsubscribe.current) {
unsubscribe.current();
}
};
}, [fetchMetadata]);
return metadata;
};