Skip to content

Commit

Permalink
Leverage synchronous cache adapter to load events in one go in useSub…
Browse files Browse the repository at this point in the history
…scribe hook
  • Loading branch information
pablof7z committed Feb 19, 2025
1 parent f255a07 commit d87d886
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-pugs-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nostr-dev-kit/ndk-mobile": patch
---

Leverage synchronous cache adapter to load events in one go in useSubscribe hook
14 changes: 5 additions & 9 deletions ndk-mobile/src/hooks/subscribe.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import '@bacons/text-decoder/install';
import { createStore } from 'zustand/vanilla';
import { useStore } from 'zustand';
import { NDKEvent, NDKFilter, NDKRelaySet, NDKSubscription, NDKSubscriptionOptions, wrapEvent } from '@nostr-dev-kit/ndk';
import { NDKEvent, NDKFilter, NDKRelaySet, NDKSubscription, NDKSubscriptionOptions } from '@nostr-dev-kit/ndk';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useNDK } from './ndk.js';
import { useNDKSession } from '../stores/session/index.js';

/**
* Extends NDKEvent with a 'from' method to wrap events with a kind-specific handler
*/
Expand Down Expand Up @@ -229,16 +228,10 @@ export const useSubscribe = <T extends NDKEvent>(
return;
}

// If we need to convert the event, we do so
if (opts?.wrap) event = wrapEvent<T>(event);

event.once("deleted", () => {
storeInstance.removeEventId(id);
});

// If conversion failed, we bail
if (!event) return;

storeInstance.addEvent(event as T);
eventIds.current.set(id, event.created_at!);
},
Expand Down Expand Up @@ -268,7 +261,10 @@ export const useSubscribe = <T extends NDKEvent>(
subscription.on('closed', handleClosed);

storeInstance.setSubscription(subscription);
subscription.start();
const cachedEvents = subscription.start(false);
if (cachedEvents) {
for (const event of cachedEvents) handleEvent(event);
}

return () => {
if (storeInstance.subscriptionRef) {
Expand Down

0 comments on commit d87d886

Please sign in to comment.