@speechmatics/flow-client-react
Version:
React hooks for interacting with the Speechmatics Flow API
63 lines (60 loc) • 1.73 kB
JavaScript
;
"use client";
import { jsx } from 'react/jsx-runtime';
import { FlowClient } from '@speechmatics/flow-client';
import { useState, useMemo, useSyncExternalStore } from 'react';
import { FlowContext } from './flow-context.js';
import { useClientEventListener } from './use-flow-event-listener.js';
function FlowProvider({
server,
children,
...options
}) {
const [client] = useState(() => {
return new FlowClient(server ?? "wss://flow.api.speechmatics.com", options);
});
const socketState = useClientSocketState(client);
const [sessionId, setSessionId] = useState();
useClientEventListener(client, "message", ({ data }) => {
if (data.message === "Error") {
console.error(data);
} else if (data.message === "ConversationStarted") {
setSessionId(data.asr_session_id);
}
});
useClientEventListener(client, "socketClose", () => {
setSessionId(void 0);
});
const value = useMemo(
() => ({
client,
socketState,
sessionId
}),
[client, socketState, sessionId]
);
return /* @__PURE__ */ jsx(FlowContext.Provider, { value, children });
}
const SOCKET_EVENTS = [
"socketInitialized",
"socketOpen",
"socketClosing",
"socketClose",
"socketError"
];
function useClientSocketState(client) {
const subscribe = (onChange) => {
for (const e of SOCKET_EVENTS) {
client.addEventListener(e, onChange);
}
return () => {
for (const e of SOCKET_EVENTS) {
client.removeEventListener(e, onChange);
}
};
};
const getSnapshot = () => client.socketState;
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
export { FlowProvider };
//# sourceMappingURL=flow-provider.js.map