update layout

This commit is contained in:
Ren Amamiya
2023-04-25 09:33:17 +07:00
parent 50e29beda4
commit 53fd29ddb8
9 changed files with 99 additions and 34 deletions

View File

@@ -3,28 +3,42 @@ import { RelayContext } from '@components/relaysProvider';
import { DEFAULT_RELAYS } from '@stores/constants';
import { updateChannelMetadata } from '@utils/storage';
import { getChannel } from '@utils/storage';
import { useCallback, useContext, useEffect, useState } from 'react';
export const useChannelMetadata = (id: string, fallback: any) => {
export const useChannelMetadata = (id: string) => {
const pool: any = useContext(RelayContext);
const [metadata, setMetadata] = useState(fallback);
const [metadata, setMetadata] = useState(null);
const fetchMetadata = useCallback(() => {
const fetchFromRelay = useCallback(() => {
const unsubscribe = pool.subscribe(
[
{
kinds: [41],
'#e': [id],
},
{
ids: [id],
kinds: [40],
},
],
DEFAULT_RELAYS,
(event: { content: string }) => {
const json = JSON.parse(event.content);
// update state
setMetadata(json);
// update metadata in database
updateChannelMetadata(id, event.content);
(event: { kind: number; content: string }) => {
switch (event.kind) {
case 41:
const json = JSON.parse(event.content);
// update state
setMetadata(json);
// update metadata in database
updateChannelMetadata(id, event.content);
break;
case 40:
// update state
setMetadata(JSON.parse(event.content));
default:
break;
}
},
undefined,
undefined,
@@ -39,18 +53,28 @@ export const useChannelMetadata = (id: string, fallback: any) => {
};
}, [id, pool]);
const getChannelFromDB = useCallback(async () => {
return await getChannel(id);
}, [id]);
useEffect(() => {
let ignore = false;
if (!ignore) {
// fetch kind 41
fetchMetadata();
getChannelFromDB().then((res) => {
console.log(res);
if (res) {
setMetadata(JSON.parse(res.metadata));
} else {
fetchFromRelay();
}
});
}
return () => {
ignore = true;
};
}, [fetchMetadata, fallback]);
}, [fetchFromRelay, getChannelFromDB]);
return metadata;
};

View File

@@ -120,6 +120,13 @@ export async function getChannels(limit: number, offset: number) {
return await db.select(`SELECT * FROM channels ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`);
}
// get channel by id
export async function getChannel(id: string) {
const db = await connect();
const result = await db.select(`SELECT * FROM channels WHERE event_id = "${id}";`);
return result[0];
}
// create channel
export async function createChannel(event_id: string, metadata: string, created_at: number) {
const db = await connect();