Basic Usage
This example demonstrates how to use the Vocale in any React app to manage voice interactions and form submissions with Vocale.ai.
You can see a fully working example here - StackBlitz/Vocale React Example
import React, { useRef } from 'react'; import { useForm, useVoiceRecording } from '@vocale/react'; function VoiceForm() { const [name, setName] = React.useState<string>(""); const handleNameChange = (e) => setName(e.target.name); // useForm hook to manage form state and sync with Vocale const { requestCompletion, syncForm } = useForm( 'my-form', { onCompletion: (completion) => { // after running the requestCompletion function, // completions will trigger this callback // It is optional, you can use directly await the requestCompletion function. setName(completion.name); } } ); useEffect(() => { // Sync the form with Vocale. // The first time it will create it, and if it changes it will update it on the site. await syncForm({ type: 'HTML', schema: [ // Define the form schema with necessary fields // You can include text, number, boolean fields, etc. // For example: { id: 'comment', type: 'text', fieldType: 'text' }, // Other form fields... ], }); }, []) // You can use the useVoiceRecording hook to manage voice recording const { isRecording, startRecording, stopRecording } = useVoiceRecording({ onFinish: async (blob: Blob, duration: number) => { // Send the recorded audio and completed form data to Vocale for processing await requestCompletion(blob, duration, { type: 'HTML', schema: [ { id:'comment', value: name //You can send the current value so Vocale can take it into account, for example if asking by voice to fix the spelling }, // Other form fields... ] }); } }); return ( <div> <h2>Voice Comment Form</h2> <form> {/* Form fields */} {/* For example, you can have a text field for the name */} <input type="text" name="name" placeholder="Your name" value={name} onChange={handleNameChange} /> {/* Other form fields... */} {/* Button to start or stop voice recording */} {isRecording ? ( <button onClick={stopRecording}>Stop Recording</button> ) : ( <button onClick={startRecording}>Start Recording</button> )} {/* Submit button */} <button type="submit">Submit</button> </form> </div> ); } export default VoiceForm;
In this example:
- ⚙️ The hook useForm is used to manage the form state and sync it with Vocale when submitted.
- ⚙️ We use useVoiceRecording hook to handle voice recording. The user can start and stop recording by clicking a button.
- ⚙️ When submitting the form, first the form data with Vocale and then send the recorded audio along with the completed form for processing.