@sentdm/voice-client-react
v0.2.1
Published
React bindings for Sent Voice Client: a provider and hooks that re-render on call events
Readme
@sentdm/voice-client-react
React bindings for @sentdm/voice-client, the Sent Voice Client for the web.
Installation
npm install @sentdm/voice-client @sentdm/voice-client-reactUsage
@sentdm/voice-client-react wraps one client in a provider, with hooks that re-render on its events. It supports React 18 and 19.
import { SentVoiceProvider, useActiveCall, useIncomingCall, useSentVoice } from '@sentdm/voice-client-react';
const getVoiceToken = () => fetch('/api/voice-token').then((response) => response.text());
export function App() {
return (
<SentVoiceProvider tokenProvider={getVoiceToken} autoRegister={false}>
<Phone />
</SentVoiceProvider>
);
}
function Phone() {
const { client, state, register } = useSentVoice();
const invite = useIncomingCall();
const { call, state: callState, isMuted, mute, hangup, duration } = useActiveCall();
if (state !== 'registered') return <button onClick={register}>Go online</button>;
if (invite) {
return (
<p>
<button onClick={() => invite.accept()}>Answer</button>
<button onClick={() => invite.reject()}>Decline</button>
</p>
);
}
if (call) {
return (
<p>
{callState} for {duration} s <button onClick={() => mute()}>{isMuted ? 'Unmute' : 'Mute'}</button>
<button onClick={hangup}>Hang up</button>
</p>
);
}
return <button onClick={() => client?.connect({ to: 'ben' })}>Call Ben</button>;
}SentVoiceProvidertakes every client option, plusautoRegister(defaulttrue), which registers as soon as the client exists. Registering needs the notification permission, which Firefox and Safari only ask for after a user gesture, so the example registers from a click.- The client is created after the provider mounts, so its children render first, on the server too, with
clientnullandstate'unregistered'. Unmounting destroys the client and ends its calls. - Props are read once, when the client is created: remount the provider with a new
keyto change them, for example for another user.tokenProvideris the exception, the latest one is always used. useSentVoice()gives the client, its state,registerandunregister.useIncomingCall()gives the newest invite still waiting for an answer, ornull.useActiveCall()gives the active call with its state,isMuted,mute,hangup,sendDigitsandduration, the seconds since it connected.useAudioDevices()gives the microphones and speakers withsetInputandsetOutput.- The entry point is marked
'use client'for the Next.js App Router.
