Skip to content

Commit 4cb00dd

Browse files
committed
feat: add NDKHeadless component for easier NDK instantiation in React apps
1 parent c7df7f4 commit 4cb00dd

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

ndk-hooks/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export * from "./session/hooks/use-available-sessions";
2020
export * from "./subscribe/store";
2121
export * from "./wallet/hooks";
2222

23+
export * from "./ndk/headless/index.js";
24+
2325
export * from "@nostr-dev-kit/ndk";
2426
import NDK from "@nostr-dev-kit/ndk";
2527
export default NDK;

ndk-hooks/src/ndk/headless/index.tsx

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import NDK, { NDKConstructorParams } from "@nostr-dev-kit/ndk";
2+
import { NDKSessionStorageAdapter } from "../../session/storage";
3+
import { useNDKInit } from "../hooks";
4+
import { useEffect } from "react";
5+
import { useNDKSessionMonitor } from "../../session/hooks/use-ndk-session-monitor";
6+
import { SessionStartOptions } from "../../session/store/types";
7+
8+
interface NDKHeadlessProps {
9+
ndk: NDKConstructorParams;
10+
session: {
11+
storage: NDKSessionStorageAdapter;
12+
opts: SessionStartOptions;
13+
} | false;
14+
};
15+
16+
/**
17+
* Add a headless component to make it simpler to instantiate NDK in React apps.
18+
*
19+
* @example
20+
* ```tsx
21+
* import { NDKHeadless } from "@nostr-dev-kit/ndk-hooks";
22+
*
23+
* function App() {
24+
* return (
25+
* <>
26+
* <NDKHeadless
27+
* ndk={{ explicitRelayUrls: ["wss://relay.damus.io"] }}
28+
* session={{ storage: new NDKSessionLocalStorage(), opts: { follows: true, profile: true } }}
29+
* />
30+
* <YourApp />
31+
* </>
32+
* );
33+
* }
34+
*/
35+
export function NDKHeadless({
36+
ndk,
37+
session = false,
38+
}: NDKHeadlessProps) {
39+
const initNDK = useNDKInit();
40+
41+
useEffect(() => {
42+
const _ndk = new NDK(ndk);
43+
initNDK(_ndk);
44+
}, []);
45+
46+
useNDKSessionMonitor(session ? session.storage : false, session ? session.opts : undefined);
47+
48+
return null;
49+
}

0 commit comments

Comments
 (0)