Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save davidystephenson/31a2076905cac1be915a7be89094d8a0 to your computer and use it in GitHub Desktop.

Select an option

Save davidystephenson/31a2076905cac1be915a7be89094d8a0 to your computer and use it in GitHub Desktop.
import { useEffect, useState, useMemo } from "react";
function ProductList({ message }) {
const [allProducts, setAllProducts] = useState([]);
const [category, setCategory] = useState('all')
const [value, setValue] = useState(message)
useEffect(() => {
setValue(message)
}, [message])
useEffect(() => {
console.log('componentMounted')
fetch('https://fakestoreapi.com/products')
.then((response) => response.json())
.then((data) => {
setAllProducts(data)
})
}, [])
useEffect(() => {
function logWidth() {
console.log(value, window.innerWidth)
}
window.addEventListener('resize', logWidth)
// return () => {
// console.log('cleanup')
// window.removeEventListener('resize', logWidth)
// }
}, [value])
const filteredProducts = useMemo(() => {
const filtered = category === 'all'
? allProducts
: allProducts.filter(product => {
return product.category === category
})
return filtered
}, [category, allProducts])
if (allProducts.length === 0) {
return <h1>Loading...</h1>;
}
return (
<div className="product-list">
<h1>Product List</h1>
<input
value={value}
onChange={event => setValue(event.target.value)}
/>
<hr />
<select
value={category}
onChange={(event) => {
setCategory(event.target.value)
}}
>
<option value='all'>All</option>
<option value='electronics'>Electronics</option>
<option value='jewelery'>Jewelery</option>
</select>
<ul>
{filteredProducts.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
</div>
);
}
export default ProductList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment