fixed some performance issues

This commit is contained in:
Ren Amamiya
2023-04-21 15:13:33 +07:00
parent f8dff5f81e
commit 9fdf2eb81c
12 changed files with 71 additions and 62 deletions

View File

@@ -10,7 +10,7 @@
"prettier" "prettier"
], ],
"rules": { "rules": {
"@typescript-eslint/no-unused-vars": "warn", "@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "warn" "@typescript-eslint/no-explicit-any": "warn"
}, },
"ignorePatterns": ["dist", "**/*.js", "**/*.json", "node_modules"] "ignorePatterns": ["dist", "**/*.js", "**/*.json", "node_modules"]

View File

@@ -46,7 +46,7 @@ export default function Page({ params }: { params: { id: string } }) {
}, },
], ],
FULL_RELAYS, FULL_RELAYS,
(event: any) => { (event: { kind: number; tags: string[][]; pubkey: string; id: string }) => {
if (event.kind === 44) { if (event.kind === 44) {
muted.current = muted.current.add(event.tags[0][1]); muted.current = muted.current.add(event.tags[0][1]);
} else if (event.kind === 43) { } else if (event.kind === 43) {

View File

@@ -10,7 +10,7 @@ import { FULL_RELAYS } from '@stores/constants';
import useLocalStorage from '@rehooks/local-storage'; import useLocalStorage from '@rehooks/local-storage';
import { useSetAtom } from 'jotai'; import { useSetAtom } from 'jotai';
import { useResetAtom } from 'jotai/utils'; import { useResetAtom } from 'jotai/utils';
import { Suspense, useCallback, useContext, useEffect, useRef } from 'react'; import { useContext, useEffect } from 'react';
export default function Page({ params }: { params: { pubkey: string } }) { export default function Page({ params }: { params: { pubkey: string } }) {
const [pool]: any = useContext(RelayContext); const [pool]: any = useContext(RelayContext);
@@ -19,10 +19,11 @@ export default function Page({ params }: { params: { pubkey: string } }) {
const setChatMessages = useSetAtom(chatMessagesAtom); const setChatMessages = useSetAtom(chatMessagesAtom);
const resetChatMessages = useResetAtom(chatMessagesAtom); const resetChatMessages = useResetAtom(chatMessagesAtom);
const unsubscribe = useRef(null); useEffect(() => {
// reset stored messages
const fetchMessages = useCallback(() => { resetChatMessages();
unsubscribe.current = pool.subscribe( // fetch messages from relays
const unsubscribe = pool.subscribe(
[ [
{ {
kinds: [4], kinds: [4],
@@ -40,26 +41,15 @@ export default function Page({ params }: { params: { pubkey: string } }) {
setChatMessages((data) => [...data, event]); setChatMessages((data) => [...data, event]);
} }
); );
}, [activeAccount.pubkey, params.pubkey, pool, setChatMessages]);
useEffect(() => {
// reset stored messages
resetChatMessages();
// fetch messages from relays
fetchMessages();
return () => { return () => {
if (unsubscribe.current) { unsubscribe();
unsubscribe.current();
}
}; };
}, [fetchMessages, resetChatMessages]); }, [params.pubkey, activeAccount.pubkey, setChatMessages, pool]);
return ( return (
<div className="flex h-full w-full flex-col justify-between"> <div className="flex h-full w-full flex-col justify-between">
<Suspense fallback={<>Loading...</>}>
<MessageList /> <MessageList />
</Suspense>
<div className="shrink-0 p-3"> <div className="shrink-0 p-3">
<FormChat receiverPubkey={params.pubkey} /> <FormChat receiverPubkey={params.pubkey} />
</div> </div>

View File

@@ -70,7 +70,15 @@ export default function Page() {
}, [setData, setHasNewerNote]); }, [setData, setHasNewerNote]);
useEffect(() => { useEffect(() => {
let initPage = false;
if (!initPage) {
initialData().catch(console.error); initialData().catch(console.error);
}
return () => {
initPage = true;
};
}, [initialData]); }, [initialData]);
return ( return (

View File

@@ -103,13 +103,21 @@ export default function Page({ params }: { params: { slug: string } }) {
}, [pubkey, privkey, follows, pool, relays, router]); }, [pubkey, privkey, follows, pool, relays, router]);
useEffect(() => { useEffect(() => {
let ignore = false;
const fetchData = async () => { const fetchData = async () => {
const { data } = await supabase.from('random_users').select('pubkey').limit(28); const { data } = await supabase.from('random_users').select('pubkey').limit(28);
// update state // update state
setList((list: any) => [...list, ...data]); setList((list: any) => [...list, ...data]);
}; };
if (!ignore) {
fetchData().catch(console.error); fetchData().catch(console.error);
}
return () => {
ignore = true;
};
}, []); }, []);
return ( return (

View File

@@ -12,15 +12,16 @@ import { nip02ToArray } from '@utils/transform';
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { getPublicKey } from 'nostr-tools'; import { getPublicKey } from 'nostr-tools';
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useContext, useEffect, useRef, useState } from 'react';
export default function Page({ params }: { params: { privkey: string } }) { export default function Page({ params }: { params: { privkey: string } }) {
const [pool, relays]: any = useContext(RelayContext); const [pool, relays]: any = useContext(RelayContext);
const pubkey = useMemo(() => (params.privkey ? getPublicKey(params.privkey) : null), [params.privkey]);
const timeout = useRef(null);
const [profile, setProfile] = useState({ metadata: null }); const [profile, setProfile] = useState({ metadata: null });
const [done, setDone] = useState(false); const [done, setDone] = useState(false);
const timeout = useRef(null);
const pubkey = getPublicKey(params.privkey);
const createPlebs = useCallback(async (tags: string[]) => { const createPlebs = useCallback(async (tags: string[]) => {
for (const tag of tags) { for (const tag of tags) {
@@ -67,7 +68,7 @@ export default function Page({ params }: { params: { privkey: string } }) {
); );
return () => { return () => {
unsubscribe; unsubscribe();
clearTimeout(timeout.current); clearTimeout(timeout.current);
}; };
}, [pool, relays, pubkey, params.privkey, createPlebs]); }, [pool, relays, pubkey, params.privkey, createPlebs]);

View File

@@ -28,17 +28,17 @@ export default function Page() {
const now = useRef(new Date()); const now = useRef(new Date());
const timeout = useRef(null); const timeout = useRef(null);
const unsubscribe = useRef(null);
const fetchData = useCallback( const fetchData = useCallback(
async (account: { id: number; pubkey: string; chats: string[] }, tags: any) => { async (account: { id: number; pubkey: string; chats: string[] }, tags: any) => {
const lastLogin = await getLastLogin(); const lastLogin = await getLastLogin();
const notes = await countTotalNotes(); const notes = await countTotalNotes();
const channels = await countTotalChannels(); const channels = await countTotalChannels();
const chats = account.chats?.length || 0; const chats = account.chats?.length || 0;
const follows = JSON.parse(tags); const follows = JSON.parse(tags);
const query = []; const query = [];
let since: number; let since: number;
// kind 1 (notes) query // kind 1 (notes) query
@@ -75,7 +75,7 @@ export default function Page() {
}); });
} }
// subscribe relays // subscribe relays
unsubscribe.current = pool.subscribe( const unsubscribe = pool.subscribe(
query, query,
relays, relays,
(event: { kind: number; tags: string[]; id: string; pubkey: string; content: string; created_at: number }) => { (event: { kind: number; tags: string[]; id: string; pubkey: string; content: string; created_at: number }) => {
@@ -132,14 +132,20 @@ export default function Page() {
logAllEvents: false, logAllEvents: false,
} }
); );
return () => {
unsubscribe();
};
}, },
[router, pool, relays] [router, pool, relays]
); );
useEffect(() => { useEffect(() => {
let ignore = false;
getPlebs() getPlebs()
.then((res) => { .then((res) => {
if (res) { if (res && !ignore) {
writeStorage('plebs', res); writeStorage('plebs', res);
} }
}) })
@@ -147,7 +153,7 @@ export default function Page() {
getActiveAccount() getActiveAccount()
.then((res: any) => { .then((res: any) => {
if (res) { if (res && !ignore) {
const account = res; const account = res;
// update local storage // update local storage
writeStorage('account', account); writeStorage('account', account);
@@ -160,9 +166,7 @@ export default function Page() {
.catch(console.error); .catch(console.error);
return () => { return () => {
if (unsubscribe.current) { ignore = true;
unsubscribe.current();
}
clearTimeout(timeout.current); clearTimeout(timeout.current);
}; };
}, [fetchData, router]); }, [fetchData, router]);

View File

@@ -4,20 +4,9 @@ import { DEFAULT_AVATAR, DEFAULT_CHANNEL_BANNER } from '@stores/constants';
import { useChannelMetadata } from '@utils/hooks/useChannelMetadata'; import { useChannelMetadata } from '@utils/hooks/useChannelMetadata';
import { useRouter } from 'next/navigation';
import { useCallback } from 'react';
export const BrowseChannelItem = ({ data }: { data: any }) => { export const BrowseChannelItem = ({ data }: { data: any }) => {
const router = useRouter();
const channel = useChannelMetadata(data.event_id, data.metadata); const channel = useChannelMetadata(data.event_id, data.metadata);
const openChannel = useCallback(
(id: string) => {
router.push(`/nostr/channels/${id}`);
},
[router]
);
return ( return (
<div className="h-64 w-full rounded-md bg-zinc-900"> <div className="h-64 w-full rounded-md bg-zinc-900">
<div className="relative h-24"> <div className="relative h-24">

View File

@@ -23,7 +23,7 @@ export default function EventCollector() {
const now = useRef(new Date()); const now = useRef(new Date());
const subscribe = useCallback(async () => { const subscribe = useCallback(async () => {
pool.subscribe( const unsubscribe = pool.subscribe(
[ [
{ {
kinds: [1, 6], kinds: [1, 6],
@@ -101,7 +101,11 @@ export default function EventCollector() {
} }
} }
); );
}, [activeAccount.follows, activeAccount.pubkey, activeAccount.id, pool, relays, setHasNewerNote]);
return () => {
unsubscribe();
};
}, [activeAccount.pubkey, activeAccount.id, follows, pool, relays, setHasNewerNote]);
useEffect(() => { useEffect(() => {
subscribe(); subscribe();

View File

@@ -15,7 +15,7 @@ import { getEventHash, signEvent } from 'nostr-tools';
import { useCallback, useContext } from 'react'; import { useCallback, useContext } from 'react';
export const FormChannel = ({ eventId }: { eventId: string | string[] }) => { export const FormChannel = ({ eventId }: { eventId: string | string[] }) => {
const [pool, relays]: any = useContext(RelayContext); const [pool]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('account', {}); const [activeAccount]: any = useLocalStorage('account', {});
const [value, setValue] = useAtom(channelContentAtom); const [value, setValue] = useAtom(channelContentAtom);
@@ -61,8 +61,8 @@ export const FormChannel = ({ eventId }: { eventId: string | string[] }) => {
activeAccount.privkey, activeAccount.privkey,
eventId, eventId,
resetChannelReply, resetChannelReply,
resetValue,
pool, pool,
relays,
]); ]);
const handleEnterPress = (e) => { const handleEnterPress = (e) => {

View File

@@ -13,7 +13,7 @@ import { getEventHash, nip04, signEvent } from 'nostr-tools';
import { useCallback, useContext } from 'react'; import { useCallback, useContext } from 'react';
export default function FormChat({ receiverPubkey }: { receiverPubkey: string }) { export default function FormChat({ receiverPubkey }: { receiverPubkey: string }) {
const [pool, relays]: any = useContext(RelayContext); const [pool]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('account', {}); const [activeAccount]: any = useLocalStorage('account', {});
const [value, setValue] = useAtom(chatContentAtom); const [value, setValue] = useAtom(chatContentAtom);
@@ -44,7 +44,7 @@ export default function FormChat({ receiverPubkey }: { receiverPubkey: string })
resetValue(); resetValue();
}) })
.catch(console.error); .catch(console.error);
}, [encryptMessage, activeAccount.privkey, activeAccount.pubkey, receiverPubkey, pool]); }, [encryptMessage, activeAccount.privkey, activeAccount.pubkey, receiverPubkey, resetValue, pool]);
const handleEnterPress = (e) => { const handleEnterPress = (e) => {
if (e.key === 'Enter' && !e.shiftKey) { if (e.key === 'Enter' && !e.shiftKey) {

View File

@@ -32,9 +32,12 @@ export const useChannelMetadata = (id: string, fallback: string) => {
logAllEvents: false, logAllEvents: false,
} }
); );
}, []); }, [id, pool, relays]);
useEffect(() => { useEffect(() => {
let ignore = false;
if (!ignore) {
if (typeof fallback === 'object') { if (typeof fallback === 'object') {
setMetadata(fallback); setMetadata(fallback);
} else { } else {
@@ -44,13 +47,15 @@ export const useChannelMetadata = (id: string, fallback: string) => {
// fetch kind 41 // fetch kind 41
fetchMetadata(); fetchMetadata();
}
return () => { return () => {
ignore = true;
if (unsubscribe.current) { if (unsubscribe.current) {
unsubscribe.current(); unsubscribe.current();
} }
}; };
}, [fetchMetadata]); }, [fetchMetadata, fallback]);
return metadata; return metadata;
}; };