'How can I search through this array in my nextjs/typescript/fetch app?
I've been trying to find ways to search through this array (CustomersList), but didn't get very far. Help would be much appreciated.
after the fetch(whats done with the response):
const data = await res.json();
return {
props: {
CustomersList: data,
}
};
How im displaying the data to the page:
<ul className="customers">
{CustomersList.map((customer) => (
<form method="POST" action={AppendUrl(customer.Id)}>
<table className="customer-list">
<tr>
<th>Customer Name:</th>
<th>Customer Id:</th>
</tr>
<tr>
<td>{customer.Name}</td>
<td>{customer.Id}</td>
<input type="submit" value="Select"/>
</tr>
</table>
</form>
))}
</ul>
I would like to add a searchbar to this to be able to search through these customers by their name (customer.Name)
Solution 1:[1]
I actually found some code that was super helpful.
search code:
//Search Customer
const [name, setName] = useState("");
const [foundCustomers, setFoundCustomers] = useState(CustomersList);
const filter = (e: { target: { value: any } }) => {
const keyword = e.target.value;
if (keyword !== "") {
const results = CustomersList.filter((customer) => {
return customer.Name.toLowerCase().startsWith(keyword.toLowerCase());
// Use the toLowerCase() method to make it case-insensitive
});
setFoundCustomers(results);
} else {
setFoundCustomers(CustomersList);
// If the text field is empty, show all users
}
setName(keyword);
};
searchbox input code:
<ul className="customers">
<input
type="search"
value={name}
onChange={filter}
className="input"
placeholder="Customer Name"
/>
{foundCustomers && foundCustomers.length > 0 ? (
foundCustomers.map((customer) => (
<form method="POST" action={AppendUrl(customer.Id)}>
<table className="customer-list">
<>
<tr>
<th>Customer Name:</th>
<th>Customer Id:</th>
</tr>
<tr>
<td>{customer.Name}</td>
<td>{customer.Id}</td>
<input type="submit" value="Select" />
</tr>
</>
</table>
</form>
))
) : (
<h1>No results found!</h1>
)}
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | max14 |
