feat: Add filter products
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { ProductCards } from "./components";
|
||||
import { useEffect, useState } from "react";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import type { Product, ProductLine } from "../../types";
|
||||
import Order from "./components/order/Order";
|
||||
import styles from "./Catalog.module.css";
|
||||
@@ -8,6 +8,7 @@ import styles from "./Catalog.module.css";
|
||||
const Catalog = () => {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [productLines, setProductLines] = useState<ProductLine[] | []>([]);
|
||||
const [filterText, setFilterText] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchProducts() {
|
||||
@@ -22,7 +23,7 @@ const Catalog = () => {
|
||||
fetchProducts();
|
||||
}, []);
|
||||
|
||||
function addProductLine(product: Product, quantity: number){
|
||||
function addProductLine(product: Product, quantity: number): void{
|
||||
const newProductLine: ProductLine = {
|
||||
id: Date.now(),
|
||||
product: product,
|
||||
@@ -34,10 +35,30 @@ const Catalog = () => {
|
||||
setProductLines([...productLines, newProductLine]);
|
||||
}
|
||||
|
||||
const filteredProducts = useMemo(() =>
|
||||
filterText.trim()
|
||||
? products.filter(p =>
|
||||
p.name.toLowerCase().includes(filterText.toLowerCase())
|
||||
)
|
||||
: products,
|
||||
[products, filterText]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.layout}>
|
||||
<section className={styles.catalog}>
|
||||
<ProductCards products={products} addProductLine={addProductLine}/>
|
||||
<section>
|
||||
<form onSubmit={e => e.preventDefault()}>
|
||||
<input
|
||||
type="text"
|
||||
value={filterText}
|
||||
placeholder="Buscar"
|
||||
onChange={
|
||||
(event) => setFilterText(event.target.value)}/>
|
||||
<button type="submit">Buscar</button>
|
||||
</form>
|
||||
</section>
|
||||
<ProductCards products={filteredProducts} addProductLine={addProductLine}/>
|
||||
</section>
|
||||
<aside className={styles.order}>
|
||||
<Order productLines={productLines}/>
|
||||
|
||||
Reference in New Issue
Block a user