Skip to content

Hands-free form

Asks one question after the other, with a plain for loop.

Live demo, needs a microphone.Open full screen ↗
  1. Each field is one await listen(). The loop moves on when the user stops talking.
  2. An AbortController cancels the whole sequence: pass its signal.
  3. Leaving the screen aborts the same controller, so the microphone never stays open.

Uses

This file is what runs in the phone: the page reads it from the repository.

example/scenes/form.tsx
import { listen, SpeechError } from 'expo-stt';
import { useEffect, useRef, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
import { ErrorNote, IconButton, Screen, useDemo } from './ui';
const PLUM = '#5b2a6e';
const FIELDS = [
{ key: 'name', label: 'Name', hint: 'Who is the table for?' },
{ key: 'guests', label: 'Guests', hint: 'How many of you?' },
{ key: 'time', label: 'Day and time', hint: 'When are you coming?' },
{ key: 'wishes', label: 'Wishes', hint: 'Allergies, a window seat…' },
] as const;
type Key = (typeof FIELDS)[number]['key'];
const EMPTY: Record<Key, string> = { name: '', guests: '', time: '', wishes: '' };
/** Hands-free form: one question after the other, with async/await. */
export function Form() {
const { locale } = useDemo();
const [values, setValues] = useState(EMPTY);
const [active, setActive] = useState<Key | null>(null);
const [error, setError] = useState<SpeechError | null>(null);
const abortion = useRef<AbortController | null>(null);
// Leaving the screen ends the session.
useEffect(() => () => abortion.current?.abort(), []);
const set = (key: Key, value: string) => setValues((previous) => ({ ...previous, [key]: value }));
const fill = async (keys: readonly Key[]) => {
const controller = new AbortController();
abortion.current = controller;
setError(null);
try {
for (const key of keys) {
setActive(key);
const { transcript } = await listen({
locale,
silenceTimeout: 1500,
signal: controller.signal,
onInterim: (text) => set(key, text),
});
set(key, transcript.replace(/\.$/, ''));
}
} catch (cause) {
setError(SpeechError.from(cause));
} finally {
setActive(null);
}
};
return (
<Screen title="Hands-free form" color={PLUM} background="#f9f1fb">
<ScrollView contentContainerStyle={styles.form} keyboardShouldPersistTaps="handled">
<Text style={styles.heading}>Book a table</Text>
{FIELDS.map(({ key, label, hint }) => {
const isActive = active === key;
return (
<View key={key} style={[styles.field, isActive && styles.fieldActive]}>
<View style={styles.grow}>
<Text style={styles.label}>{label}</Text>
<TextInput
accessibilityLabel={label}
editable={active === null}
onChangeText={(text) => set(key, text)}
placeholder={isActive ? 'Listening…' : hint}
placeholderTextColor="#8d6f99"
style={styles.input}
value={values[key]}
/>
</View>
<IconButton
icon={isActive ? 'stop' : 'mic'}
label={isActive ? 'Cancel' : `Dictate ${label}`}
color={isActive ? '#fff' : PLUM}
background={isActive ? '#c8412b' : '#eedcf3'}
size={44}
disabled={active !== null && !isActive}
onPress={() => (isActive ? abortion.current?.abort() : void fill([key]))}
/>
</View>
);
})}
</ScrollView>
<ErrorNote error={error} />
<Pressable
accessibilityRole="button"
onPress={() => (active ? abortion.current?.abort() : void fill(FIELDS.map(({ key }) => key)))}
style={[styles.button, active !== null && styles.cancel]}
>
<Text style={styles.buttonText}>{active ? 'Cancel' : 'Fill everything by voice'}</Text>
</Pressable>
</Screen>
);
}
const styles = StyleSheet.create({
form: { padding: 16, gap: 12 },
heading: { color: PLUM, fontSize: 32, fontWeight: '800', marginBottom: 6 },
grow: { flex: 1, minWidth: 0 },
field: {
flexDirection: 'row',
alignItems: 'center',
gap: 10,
padding: 14,
borderRadius: 18,
borderWidth: 2,
borderColor: 'transparent',
backgroundColor: '#fff',
},
fieldActive: { borderColor: '#c8412b' },
label: { color: '#7a5588', fontSize: 13, fontWeight: '600' },
input: { color: '#2c1437', fontSize: 18, paddingVertical: 6 },
button: { margin: 16, padding: 18, borderRadius: 20, alignItems: 'center', backgroundColor: PLUM },
cancel: { backgroundColor: '#c8412b' },
buttonText: { color: '#fff', fontSize: 17, fontWeight: '700' },
});