mkstack/src/components/NostrProvider.tsx

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-06-02 21:44:52 -05:00
import React, { useEffect, useRef } from 'react';
2025-04-16 21:43:54 -05:00
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
2025-06-02 21:44:52 -05:00
import { useQueryClient } from '@tanstack/react-query';
import { useAppConfig } from './AppProvider';
2025-04-16 21:43:54 -05:00
interface NostrProviderProps {
children: React.ReactNode;
}
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
2025-06-02 21:44:52 -05:00
const { children } = props;
const { config, availableRelays } = useAppConfig();
const queryClient = useQueryClient();
2025-04-16 21:43:54 -05:00
// Create NPool instance only once
const pool = useRef<NPool | undefined>(undefined);
2025-06-02 21:44:52 -05:00
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
const available = useRef(availableRelays);
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
available.current = availableRelays;
queryClient.resetQueries();
}, [config.relayUrl, availableRelays, queryClient]);
// Initialize NPool only once
2025-04-16 21:43:54 -05:00
if (!pool.current) {
pool.current = new NPool({
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
2025-06-02 21:44:52 -05:00
return new Map([[relayUrl.current, filters]]);
2025-04-16 21:43:54 -05:00
},
eventRouter(_event: NostrEvent) {
2025-06-02 21:44:52 -05:00
return available.current.map((info) => info.url);
2025-04-16 21:43:54 -05:00
},
});
}
return (
<NostrContext.Provider value={{ nostr: pool.current }}>
{children}
</NostrContext.Provider>
);
};
export default NostrProvider;