mkstack/src/hooks/useNostrPublish.ts

42 lines
1.3 KiB
TypeScript
Raw Normal View History

import { useNostr } from "@nostrify/react";
2025-05-30 23:40:57 +02:00
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useCurrentUser } from "./useCurrentUser";
2025-05-30 23:40:57 +02:00
import type { NostrEvent } from "@nostrify/nostrify";
2025-05-30 23:40:57 +02:00
export function useNostrPublish(): UseMutationResult<NostrEvent> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
2025-05-30 23:40:57 +02:00
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
if (user) {
const tags = t.tags ?? [];
// Add the client tag if it doesn't exist
if (location.protocol === "https:" && !tags.some(([name]) => name === "client")) {
2025-06-02 22:05:03 -05:00
tags.push(["client", location.hostname]);
}
const event = await user.signer.signEvent({
kind: t.kind,
content: t.content ?? "",
tags,
created_at: t.created_at ?? Math.floor(Date.now() / 1000),
});
2025-04-23 15:13:17 -05:00
await nostr.event(event, { signal: AbortSignal.timeout(5000) });
2025-05-30 23:40:57 +02:00
return event;
} else {
throw new Error("User is not logged in");
}
},
onError: (error) => {
console.error("Failed to publish event:", error);
},
onSuccess: (data) => {
console.log("Event published successfully:", data);
},
});
}