Skip to content

Instantly share code, notes, and snippets.

@maryojo
Last active May 16, 2024 07:39
Show Gist options
  • Save maryojo/0c8f146a4ac28de768161a6c0906a453 to your computer and use it in GitHub Desktop.
Save maryojo/0c8f146a4ac28de768161a6c0906a453 to your computer and use it in GitHub Desktop.
ProductCard Component without SRP
export default function ProductCard() {
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/${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 (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>{product.price}</p>
{isAddingToCart ? (
<p>Adding to cart...</p>
) : error ? (
<p className="error">{error}</p>
) : (
<button onClick={addToCart}>Add to Cart</button>
)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment