Add publish method

This commit is contained in:
Tristan Edwards 2022-12-25 17:03:06 +01:00
parent 958eb71883
commit 352488b9f8
3 changed files with 52 additions and 19 deletions

View File

@ -1,5 +1,5 @@
<p align="center"> <p align="center">
<b>react-nostr</b> <b>nostr-react</b>
</p> </p>
<p align="center"> <p align="center">
React Hooks for Nostr ✨ React Hooks for Nostr ✨
@ -8,7 +8,7 @@ React Hooks for Nostr ✨
## Installation ## Installation
``` ```
npm install @nostrgg/react npm install nostr-react
``` ```
## Example usage: ## Example usage:
@ -16,7 +16,7 @@ npm install @nostrgg/react
Wrap your app in the NostrProvider: Wrap your app in the NostrProvider:
```tsx ```tsx
import { NostrProvider } from "@nostrgg/react"; import { NostrProvider } from "nostr-react";
const relayUrls = [ const relayUrls = [
"wss://nostr-pub.wellorder.net", "wss://nostr-pub.wellorder.net",
@ -37,12 +37,12 @@ You can now use the `useNostr` and `useNostrEvents` hooks in your components!
**Fetching all `text_note` events starting now:** **Fetching all `text_note` events starting now:**
```tsx ```tsx
import { Kind, useNostrEvents, dateToUnix } from "@nostrgg/react"; import { useNostrEvents, dateToUnix } from "nostr-react";
const GlobalFeed = () => { const GlobalFeed = () => {
const { isLoading, events } = useNostrEvents({ const { isLoading, events } = useNostrEvents({
filter: { filter: {
kinds: [Kind.TextNote], kinds: [1],
since: dateToUnix(new Date()), // all new events from now since: dateToUnix(new Date()), // all new events from now
}, },
}); });
@ -60,7 +60,7 @@ const GlobalFeed = () => {
**Fetching all `text_note` events from a specific user, since the beginning of time:** **Fetching all `text_note` events from a specific user, since the beginning of time:**
```tsx ```tsx
import { Kind, useNostrEvents, dateToUnix } from "@nostrgg/react"; import { useNostrEvents, dateToUnix } from "nostr-react";
const ProfileFeed = () => { const ProfileFeed = () => {
const { events } = useNostrEvents({ const { events } = useNostrEvents({
@ -69,7 +69,7 @@ const ProfileFeed = () => {
"9c2a6495b4e3de93f3e1cc254abe4078e17c64e5771abc676a5e205b62b1286c", "9c2a6495b4e3de93f3e1cc254abe4078e17c64e5771abc676a5e205b62b1286c",
], ],
since: 0, since: 0,
kinds: [Kind.TextNote], kinds: [1],
}, },
}); });
@ -87,32 +87,46 @@ const ProfileFeed = () => {
```tsx ```tsx
import { import {
generateSignedEvent,
Kind,
SendMsgType,
useNostr, useNostr,
} from "@nostrgg/react"; } from "@nostrgg/react";
import {
type Event as NostrEvent,
getEventHash,
getPublicKey,
signEvent,
} from "nostr-tools";
export default function PostButton() { export default function PostButton() {
const { sendEvent } = useNostr(); const { publish } = useNostr();
const onPost = async () => { const onPost = async () => {
const privKey = prompt("Paste your private key here:"); const privKey = prompt("Paste your private key:");
if (!privKey) { if (!privKey) {
alert("no private key provided"); alert("no private key provided");
return; return;
} }
const event = { const message = prompt("Enter the message you want to send:");
content: "Hello world!",
kind: Kind.TextNote, if (!message) {
alert("no message provided");
return;
}
const event: NostrEvent = {
content: message,
kind: 1,
tags: [], tags: [],
created_at: Math.floor(Date.now() / 1000),
pubkey: getPublicKey(privKey),
}; };
const signedEvent = await generateSignedEvent(event, privKey); event.id = getEventHash(event);
event.sig = signEvent(event, privKey);
sendEvent?.([SendMsgType.EVENT, signedEvent]); publish(event);
}; };
return ( return (

View File

@ -9,6 +9,7 @@ import {
import { Relay, Filter, Event as NostrEvent, relayInit } from "nostr-tools" import { Relay, Filter, Event as NostrEvent, relayInit } from "nostr-tools"
import { uniqBy } from "./utils" import { uniqBy } from "./utils"
export { dateToUnix } from "./utils"
type OnConnectFunc = (relay: Relay) => void type OnConnectFunc = (relay: Relay) => void
@ -17,12 +18,14 @@ interface NostrContextType {
debug?: boolean debug?: boolean
connectedRelays: Relay[] connectedRelays: Relay[]
onConnect: (_onConnectCallback?: OnConnectFunc) => void onConnect: (_onConnectCallback?: OnConnectFunc) => void
publish: (event: NostrEvent) => void
} }
const NostrContext = createContext<NostrContextType>({ const NostrContext = createContext<NostrContextType>({
isLoading: true, isLoading: true,
connectedRelays: [], connectedRelays: [],
onConnect: () => null, onConnect: () => null,
publish: () => null,
}) })
const log = ( const log = (
@ -34,8 +37,6 @@ const log = (
console[type](...args) console[type](...args)
} }
// TODO: add "send"
export function NostrProvider({ export function NostrProvider({
children, children,
relayUrls, relayUrls,
@ -48,6 +49,12 @@ export function NostrProvider({
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [connectedRelays, setConnectedRelays] = useState<Relay[]>([]) const [connectedRelays, setConnectedRelays] = useState<Relay[]>([])
const publish = (event: NostrEvent) => {
return connectedRelays.map((relay) => {
return relay.publish(event)
})
}
let onConnectCallback: null | OnConnectFunc = null let onConnectCallback: null | OnConnectFunc = null
useEffect(() => { useEffect(() => {
@ -62,6 +69,11 @@ export function NostrProvider({
setConnectedRelays((prev) => uniqBy([...prev, relay], "url")) setConnectedRelays((prev) => uniqBy([...prev, relay], "url"))
}) })
relay.on("disconnect", () => {
log(debug, "warn", `👋 nostr: Connection closed for ${relayUrl}`)
setConnectedRelays((prev) => prev.filter((r) => r.url !== relayUrl))
})
// Wait for this to be merged: https://github.com/fiatjaf/nostr-tools/pull/69 // Wait for this to be merged: https://github.com/fiatjaf/nostr-tools/pull/69
// relay.on("error", () => { // relay.on("error", () => {
// log(debug, "error", `❌ nostr: Error connecting to ${relayUrl}!`) // log(debug, "error", `❌ nostr: Error connecting to ${relayUrl}!`)
@ -74,6 +86,7 @@ export function NostrProvider({
debug, debug,
isLoading, isLoading,
connectedRelays, connectedRelays,
publish,
onConnect: (_onConnectCallback?: OnConnectFunc) => { onConnect: (_onConnectCallback?: OnConnectFunc) => {
if (_onConnectCallback) { if (_onConnectCallback) {
onConnectCallback = _onConnectCallback onConnectCallback = _onConnectCallback

View File

@ -9,3 +9,9 @@ export const uniqBy = <T>(arr: T[], key: keyof T): T[] => {
), ),
) )
} }
export const dateToUnix = (_date?: Date) => {
const date = _date || new Date()
return Math.floor(date.getTime() / 1000)
}