Live search
Calls an API when typing stops, with loading, empty and error states. Search for “error” to see it fail.
How it works
Section titled “How it works”searchDelay={350}runsonSearch350 ms after the last key, without closing the keyboard.- The request number drops answers that arrive after a newer question.
try/catchturns a failure into a state. “Try again” callssearch()through the ref.
Uses
Full source
Section titled “Full source”This is the code running in the phone. Copy it into your app.
import { useRef, useState } from 'react';import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';import Search from 'react-native-search-box';
const BOOKS = [ { title: 'Dubliners', author: 'James Joyce' }, { title: 'Emma', author: 'Jane Austen' }, { title: 'Frankenstein', author: 'Mary Shelley' }, { title: 'Hamlet', author: 'William Shakespeare' }, { title: 'Middlemarch', author: 'George Eliot' }, { title: 'Moby-Dick', author: 'Herman Melville' }, { title: 'Persuasion', author: 'Jane Austen' }, { title: 'The Odyssey', author: 'Homer' }, { title: 'The Trial', author: 'Franz Kafka' }, { title: 'Ulysses', author: 'James Joyce' },];
type Book = (typeof BOOKS)[number];
/** Stands in for your API. Takes a moment, and fails when you search for "error". */async function searchBooks(query: string): Promise<Book[]> { await new Promise((resolve) => setTimeout(resolve, 600)); const text = query.toLowerCase(); if (text === 'error') throw new Error('The server did not answer.'); return BOOKS.filter((book) => `${book.title} ${book.author}`.toLowerCase().includes(text));}
type State = | { status: 'idle' } | { status: 'loading' } | { status: 'done'; query: string; books: Book[] } | { status: 'error'; message: string };
export default function LiveSearch() { const box = useRef<Search>(null); const lastRequest = useRef(0); const [state, setState] = useState<State>({ status: 'idle' });
const run = async (text: string) => { const query = text.trim(); const request = ++lastRequest.current; if (!query) return setState({ status: 'idle' }); setState({ status: 'loading' }); let next: State; try { next = { status: 'done', query, books: await searchBooks(query) }; } catch (error) { next = { status: 'error', message: (error as Error).message }; } // A slow answer must not overwrite the answer to a newer question. if (request === lastRequest.current) setState(next); }; const reset = () => void run('');
return ( <View style={styles.screen}> <Search ref={box} backgroundColor="#1d4ed8" placeholder="Title or author (try “error”)" placeholderAlign="left" inputHeight={38} inputBorderRadius={19} inputStyle={styles.input} searchIconExpandedMargin={16} placeholderExpandedMargin={34} searchDelay={350} onSearch={run} onDelete={reset} onCancel={reset} /> {state.status === 'idle' && <Text style={styles.hint}>Results appear when you stop typing.</Text>} {state.status === 'loading' && <ActivityIndicator style={styles.spinner} color="#1d4ed8" />} {state.status === 'error' && ( <View style={styles.message}> <Text style={styles.hint}>{state.message}</Text> <Pressable accessibilityRole="button" onPress={() => void box.current?.search()} style={styles.retry} > <Text style={styles.retryText}>Try again</Text> </Pressable> </View> )} {state.status === 'done' && ( <FlatList data={state.books} keyExtractor={(book) => book.title} keyboardShouldPersistTaps="handled" renderItem={({ item }) => ( <View style={styles.row}> <Text style={styles.title}>{item.title}</Text> <Text style={styles.author}>{item.author}</Text> </View> )} ListEmptyComponent={<Text style={styles.hint}>Nothing found for “{state.query}”.</Text>} /> )} </View> );}
const styles = StyleSheet.create({ screen: { flex: 1, backgroundColor: '#fff' }, input: { fontSize: 16, color: '#111' }, hint: { padding: 32, textAlign: 'center', color: '#6b7280' }, spinner: { margin: 32 }, message: { alignItems: 'center' }, retry: { paddingHorizontal: 20, paddingVertical: 10, borderRadius: 20, backgroundColor: '#1d4ed8' }, retryText: { color: '#fff', fontWeight: '600' }, row: { padding: 14, borderBottomWidth: 1, borderColor: '#eee' }, title: { fontSize: 16, fontWeight: '600', color: '#111' }, author: { marginTop: 2, color: '#6b7280' },});