Skip to content

Instantly share code, notes, and snippets.

@shearichard
Last active November 20, 2024 04:17
Show Gist options
  • Save shearichard/27b7d8e107be47095e8430c6516cef9e to your computer and use it in GitHub Desktop.
Save shearichard/27b7d8e107be47095e8430c6516cef9e to your computer and use it in GitHub Desktop.
A React component prepared for the Django+HTMX demo (not tested)
/////////////////////////////////////////////////////////////////////
// This component was written in haste and has not been tested
/////////////////////////////////////////////////////////////////////
import React, { useState, useEffect } from 'react';
const SearchContacts = () => {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Fetch data from the /search endpoint
useEffect(() => {
if (query.length < 1) {
setResults([]);
return;
}
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/search?q=${encodeURIComponent(query)}`);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const data = await response.json();
setResults(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const debounceTimeout = setTimeout(() => {
fetchData();
}, 300); // Add a debounce delay of 300ms
return () => clearTimeout(debounceTimeout); // Clean up timeout
}, [query]);
return (
<div>
<label htmlFor="search-input">Search Contacts:</label>
<input
id="search-input"
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Type to search..."
/>
{loading && <p>Loading...</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
{!loading && results.length > 0 && (
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{results.map((contact, index) => (
<tr key={index}>
<td>{contact.first_name}</td>
<td>{contact.last_name}</td>
<td>{contact.email}</td>
</tr>
))}
</tbody>
</table>
)}
{!loading && results.length === 0 && query && <p>No results found</p>}
</div>
);
};
export default SearchContacts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment