refactor useMetadata hook and minor fixes

This commit is contained in:
Ren Amamiya
2023-04-14 08:52:53 +07:00
parent 2fced53a60
commit cb35c70351
3 changed files with 49 additions and 28 deletions

View File

@@ -1,5 +1,6 @@
import useLocalStorage from '@rehooks/local-storage';
import { fetch } from '@tauri-apps/api/http';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
export const fetchMetadata = async (pubkey: string) => {
const result = await fetch(`https://rbr.bio/${pubkey}/metadata.json`, {
@@ -10,32 +11,50 @@ export const fetchMetadata = async (pubkey: string) => {
};
export const useMetadata = (pubkey) => {
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [plebs] = useLocalStorage('activeAccountFollows', []);
const [profile, setProfile] = useState(null);
const getCachedMetadata = useCallback(async () => {
const { getPlebByPubkey } = await import('@utils/bindings');
getPlebByPubkey({ pubkey: pubkey })
.then((res) => {
if (res && res.metadata.length > 0) {
const metadata = JSON.parse(res.metadata);
// update state
setProfile(metadata);
} else {
fetchMetadata(pubkey).then((res: any) => {
if (res) {
const metadata = JSON.parse(res.content);
// update state
setProfile(metadata);
}
});
}
})
.catch(console.error);
}, [pubkey]);
const cacheProfile = useMemo(() => {
const findInStorage = plebs.find((item) => item.pubkey === pubkey);
if (findInStorage !== undefined) {
return JSON.parse(findInStorage.metadata);
} else {
return false;
}
}, [plebs, pubkey]);
const insertPlebToDB = useCallback(
async (pubkey: string, metadata: string) => {
const { createPleb } = await import('@utils/bindings');
return await createPleb({
pleb_id: pubkey + '-lume' + activeAccount.id,
pubkey: pubkey,
kind: 1,
metadata: metadata,
account_id: activeAccount.id,
}).catch(console.error);
},
[activeAccount.id]
);
useEffect(() => {
getCachedMetadata().catch(console.error);
}, [getCachedMetadata]);
if (!cacheProfile) {
fetchMetadata(pubkey)
.then((res: any) => {
// update state
setProfile(JSON.parse(res.content));
// save to db
insertPlebToDB(pubkey, res.content);
})
.catch(console.error);
}
}, [cacheProfile, insertPlebToDB, pubkey]);
return profile;
if (cacheProfile) {
return cacheProfile;
} else {
return profile;
}
};