@msquared/etherbase-client
Version:
React hooks for interacting with Etherbase smart contracts
40 lines (39 loc) • 1.46 kB
JavaScript
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useEtherbaseContext } from "../EtherbaseProvider";
import { WebSocketManager } from "./WebSocketManager";
export default function useEtherbaseEvents({ contractAddress, events, onEvent, }) {
useEtherbaseContext();
const [error, setError] = useState(null);
const localIdRef = useRef(Math.random().toString(36).substring(2, 15));
// Stabilize the error handling wrapper function
const handleEvent = useCallback((event) => {
try {
onEvent(event);
}
catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
}, [onEvent]);
// biome-ignore lint/correctness/useExhaustiveDependencies: want to minimize re-subscriptions
useEffect(() => {
if (!contractAddress) {
setError("No contract address provided");
return;
}
const localId = localIdRef.current;
WebSocketManager.get()
.addEventSubscription(localId, {
contractAddress,
events,
onEvent: handleEvent,
})
.catch((err) => {
setError(err instanceof Error ? err.message : String(err));
});
return () => {
WebSocketManager.get().removeSubscription(localId);
};
}, [contractAddress, JSON.stringify(events), handleEvent]);
return { error };
}