← Back to Chapters

Search with API in React Native

? Search with API in React Native

? Quick Overview

Searching with an API in React Native allows users to fetch filtered data dynamically from a backend server. Common examples include product search, user lookup, or searching posts from a remote API.

? Key Concepts

  • Using TextInput to capture search text
  • Calling REST APIs with fetch()
  • Handling loading and empty states
  • Rendering results using FlatList

? Syntax / Theory

The basic flow is:

  1. User types text into a search field
  2. API request is triggered (on submit or debounce)
  3. Response data is stored in state
  4. UI updates automatically with results

? Code Example(s)

? View Code Example
// React Native search using API with fetch
import React, { useState } from "react";
import { View, TextInput, FlatList, Text } from "react-native";

const SearchApiExample = () => {
  const [query, setQuery] = useState("");
  const [data, setData] = useState([]);

  const searchData = async (text) => {
    // Call API with search query
    const response = await fetch(`https://jsonplaceholder.typicode.com/users`);
    const result = await response.json();

    // Filter data based on user input
    const filtered = result.filter(item =>
      item.name.toLowerCase().includes(text.toLowerCase())
    );

    setData(filtered);
  };

  return (
    <View>
      <TextInput
        placeholder="Search user..."
        value={query}
        onChangeText={(text) => {
          setQuery(text);
          searchData(text);
        }}
      />

      <FlatList
        data={data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <Text>{item.name}</Text>
        )}
      />
    </View>
  );
};

export default SearchApiExample;

? Live Output / Explanation

What Happens?

  • User types text in the search box
  • API data is fetched once and filtered
  • Matching names are displayed instantly

? Interactive Example / Visualization

Interact with the simulator below. As you type, the system simulates an API request (with a small network delay) and updates the list dynamically.

User Directory App
⏳ Fetching API...
  • Start typing to search...

? Use Cases

  • Search users in admin apps
  • Product search in e-commerce apps
  • Finding contacts or messages
  • Filtering API-driven lists

✅ Tips & Best Practices

  • Use debouncing to reduce API calls
  • Show a loading indicator for better UX
  • Handle empty results gracefully
  • Cache API responses when possible

? Try It Yourself

  • Add a loading spinner while fetching data
  • Implement debounce using setTimeout
  • Search using email instead of name
  • Replace API with your own backend