refactor useProfile and useChannelProfile hooks

This commit is contained in:
Ren Amamiya
2023-04-27 10:28:07 +07:00
parent 8cadb7467f
commit 6918660a5c
24 changed files with 137 additions and 195 deletions

View File

@@ -0,0 +1,56 @@
import { RelayContext } from '@components/relaysProvider';
import { READONLY_RELAYS } from '@stores/constants';
import { useContext } from 'react';
import useSWRSubscription from 'swr/subscription';
export const useChannelProfile = (id: string, channelPubkey: string) => {
const pool: any = useContext(RelayContext);
const { data } = useSWRSubscription(
id
? [
{
kinds: [41],
'#e': [id],
},
{
ids: [id],
kinds: [40],
},
]
: null,
(key, { next }) => {
const unsubscribe = pool.subscribe(
key,
READONLY_RELAYS,
(event: { kind: number; pubkey: string; content: string }) => {
switch (event.kind) {
case 40:
next(null, JSON.parse(event.content));
break;
case 41:
if (event.pubkey === channelPubkey) {
next(null, JSON.parse(event.content));
}
default:
break;
}
},
undefined,
undefined,
{
unsubscribeOnEose: true,
logAllEvents: false,
}
);
return () => {
unsubscribe();
};
}
);
return data;
};

View File

@@ -0,0 +1,14 @@
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then((r: any) => r.json());
export const useProfile = (pubkey: string) => {
const { data, error } = useSWR(`https://rbr.bio/${pubkey}/metadata.json`, fetcher);
if (error) {
return error;
}
if (data) {
return JSON.parse(data.content);
}
return null;
};

View File

@@ -1,54 +0,0 @@
import { createPleb, getPleb } from '@utils/storage';
import { fetch } from '@tauri-apps/api/http';
import { useCallback, useEffect, useState } from 'react';
export const fetchProfileMetadata = async (pubkey: string) => {
const result = await fetch(`https://rbr.bio/${pubkey}/metadata.json`, {
method: 'GET',
timeout: 5,
});
return await result.data;
};
export const useProfileMetadata = (pubkey: string) => {
const [profile, setProfile] = useState(null);
const getProfileFromDB = useCallback(async (pubkey: string) => {
return await getPleb(pubkey);
}, []);
const insertPlebToDB = useCallback(async (pubkey: string, metadata: string) => {
return createPleb(pubkey, metadata);
}, []);
useEffect(() => {
let ignore = false;
if (!ignore) {
getProfileFromDB(pubkey)
.then((res: any) => {
if (res) {
// update state
setProfile(JSON.parse(res.metadata));
} else {
fetchProfileMetadata(pubkey).then((res: any) => {
if (res) {
// update state
setProfile(JSON.parse(res.content));
// insert to db
insertPlebToDB(pubkey, res.content);
}
});
}
})
.catch(console.error);
}
return () => {
ignore = true;
};
}, [getProfileFromDB, insertPlebToDB, pubkey]);
return profile;
};