Skip to content

Instantly share code, notes, and snippets.

@maryojo
Last active May 16, 2024 07:43
Show Gist options
  • Save maryojo/7740f3dbf1fae3371fd77fa38312aeff to your computer and use it in GitHub Desktop.
Save maryojo/7740f3dbf1fae3371fd77fa38312aeff to your computer and use it in GitHub Desktop.
ProductCard with SRP
import ProductCard from './ProductCard';
export default function ParentContainerComponent() {
const [product, setProduct] = useState(null);
const [isAddingToCart, setIsAddingToCart] = useState(false);
const [error, setError] = useState(null);
const addToCart = async () => {
setIsAddingToCart(true);
try {
const response = await fetch(`/api/cart/${props.product.id}`, {
method: 'POST',
});
if (response.ok) {
setProduct(response.data);
} else {
setError("Error adding to cart");
}
} catch (error) {
setError("Error adding to cart");
} finally {
setIsAddingToCart(false);
}
};
return (
<ProductCard product={product} onClick={addToCart}/>
);
}
export default function ProductCard(product, onClick) {
return (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>{product.price}</p>
<button onClick={onClick}>Add to Cart</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment