react-adonis-transmit
Version:
React context and hooks for Adonis Transmit
95 lines (94 loc) • 2.77 kB
JavaScript
// src/TransmitContext.tsx
import React, { createContext, useContext, useEffect, useRef, useCallback } from "react";
import { Transmit } from "@adonisjs/transmit-client";
var TransmitContext = createContext(null);
function TransmitProvider({
children,
baseUrl,
onMessage,
authHeader,
enableLogging = false
}) {
const transmit = useRef(
new Transmit({
baseUrl,
beforeSubscribe: (requestInit) => {
if (authHeader) {
requestInit.headers.append("Authorization", authHeader);
}
}
})
).current;
const subscriptions = useRef(/* @__PURE__ */ new Map());
useEffect(() => {
const onUnmount = () => {
if (enableLogging) {
console.log("[Transmit] - Closing connection");
}
};
if (enableLogging) {
transmit.on("connected", () => console.log("[SSE] connected"));
transmit.on("disconnected", () => console.log("[SSE] disconnected"));
transmit.on("initializing", () => console.log("[SSE] initializing..."));
transmit.on("reconnecting", () => console.log("[SSE] reconnecting..."));
}
return () => {
onUnmount();
};
}, []);
const handleMessage = (channel, event) => {
if (enableLogging) {
console.log(`[Transmit] ${channel} message:`, event);
}
onMessage == null ? void 0 : onMessage(channel, event);
};
const subscribe = useCallback((channel, callback) => {
if (enableLogging) {
console.log("[Transmit] - Subscribing to", channel);
}
let sub = subscriptions.current.get(channel);
if (!sub) {
sub = {
count: 0,
subscription: transmit.subscription(channel)
};
subscriptions.current.set(channel, sub);
sub.subscription.onMessage((event) => {
handleMessage(channel, event);
callback(event);
});
(async () => {
try {
await sub.subscription.create();
} catch (error) {
console.error("Failed to create subscription:", error);
}
})();
}
sub.count++;
if (enableLogging) {
console.log("[Transmit] - Subscribed to", channel);
}
return () => {
if (!subscriptions.current.has(channel)) return;
const sub2 = subscriptions.current.get(channel);
sub2.count--;
if (sub2.count === 0) {
sub2.subscription.delete();
subscriptions.current.delete(channel);
}
};
}, []);
return /* @__PURE__ */ React.createElement(TransmitContext.Provider, { value: { transmit, subscribe } }, children);
}
function useTransmit() {
const context = useContext(TransmitContext);
if (!context) {
throw new Error("useTransmit must be used within a TransmitProvider");
}
return context;
}
export {
TransmitProvider,
useTransmit
};