Search Feature with API Integration
In this example, we enhance the search functionality by fetching user data from the Random User API and filtering the results based on the user’s search query.
Example: Below is an example to implementing a search feature with API integration and React Hooks:
Javascript
import React, { useState, useEffect } from 'react' ; function SearchFeatureWithRandomUserAPI() { const [query, setQuery] = useState( '' ); const [results, setResults] = useState([]); useEffect(() => { async function fetchData() { try { const response = await fetch(`https: //randomuser.me/api/?results=5000`); const data = await response.json(); setResults(data.results); } catch (error) { console.error( 'Error fetching data:' , error); } } fetchData(); }, []); const filteredResults = results.filter(user => user.name.first.toLowerCase().includes(query.toLowerCase()) || user.name.last.toLowerCase().includes(query.toLowerCase()) ); return ( <div> <input type= "text" placeholder= "Search..." value={query} onChange={(e) => setQuery(e.target.value)} /> <ul> {filteredResults.map((user, index) => ( <li key={index}> {user.name.first} {user.name.last} </li> ))} </ul> </div> ); } export default SearchFeatureWithRandomUserAPI; |
Output:
Explanation of Output:
- We declare state variables query and results using the useState hook. query stores the search query entered by the user, and results stores the fetched user data.
- Inside the useEffect hook, we use the fetch API to make an asynchronous call to the Random User API endpoint. We specify the number of results we want to fetch (100 in this case). The fetched data is then stored in the results state.
- The useEffect hook is set to run once when the component mounts, as indicated by the empty dependency array [ ].
- As the user types in the search input, the query state is updated accordingly. We filter the results array based on the search query using the filter method.
- The filtered user data is displayed as a list below the search input, showing the first and last names of the users that match the search query.
How to Build a Search Filter using React Hooks ?
In modern web development, implementing a search feature is a common requirement for various applications. With React Hooks, developers can efficiently manage state and lifecycle events, making it an ideal choice for building interactive user interfaces, including search functionalities. In this article, we’ll explore how to implement a search feature using React Hooks.
We will discuss the following two approaches for implementing Search Filter with React Hooks
Table of Content
- Basic Search Implementation
- Search Feature with API Integration