Skip to content

Commit

Permalink
🔨 Filtrando títulos con JavaScript
Browse files Browse the repository at this point in the history
  • Loading branch information
Klauditha committed Dec 5, 2023
1 parent b3186d3 commit d814c12
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
16 changes: 14 additions & 2 deletions src/Context/Context.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export const ShoppingCartProvider = ({ children }) => {

//Get products
const [items, setItems] = useState(null);
const [filteredItems, setFilteredItems] = useState(null);

//Get products by title
const [seachByTitle, setSeachByTitle] = useState(null);
console.log('seachByTitle: ', seachByTitle);


useEffect(() => {
fetch('https://api.escuelajs.co/api/v1/products')
.then((res) => res.json())
Expand All @@ -41,6 +41,17 @@ export const ShoppingCartProvider = ({ children }) => {
});
}, []);

const filteredItemsByTitle = (items, searchByTitle) => {
return items?.filter(item => item.title.toLowerCase().includes(searchByTitle.toLowerCase()));
}

useEffect(() => {
if(seachByTitle) {
setFilteredItems(filteredItemsByTitle(items, seachByTitle));
}
},[items, seachByTitle]);


return (
<ShoppingCartContext.Provider
value={{
Expand All @@ -62,6 +73,7 @@ export const ShoppingCartProvider = ({ children }) => {
setItems,
seachByTitle,
setSeachByTitle,
filteredItems
}}
>
{children}
Expand Down
20 changes: 16 additions & 4 deletions src/Pages/Home/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ import { ShoppingCartContext } from '../../Context/Context';
const Home = () => {
const context = useContext(ShoppingCartContext);

const renderView = () => {
if (context.seachByTitle?.length > 0) {
if (context.filteredItems?.length > 0) {
return context.filteredItems?.map((item) => (
<Card key={item.id} data={item} />
));
}
else{
return <div>We did not find anything :-(</div>
}
} else {
return context.items?.map((item) => <Card key={item.id} data={item} />);
}
};
return (
<Layout>
<div className="flex w-80 relative items-center justify-center mb-4">
Expand All @@ -15,12 +29,10 @@ const Home = () => {
type="text"
placeholder="Search a product"
className="rounded-lg border border-black w-80 p-4 mb-4 focus:outline-none"
onChange={(event) =>context.setSeachByTitle(event.target.value)}
onChange={(event) => context.setSeachByTitle(event.target.value)}
/>
<div className="grid gap-4 grid-cols-4 w-full max-w-screen-lg">
{context.items?.map((item) => (
<Card key={item.id} data={item} />
))}
{renderView()}
</div>
<ProductDetail />
</Layout>
Expand Down

0 comments on commit d814c12

Please sign in to comment.