Last active
May 16, 2024 07:39
-
-
Save maryojo/0c8f146a4ac28de768161a6c0906a453 to your computer and use it in GitHub Desktop.
ProductCard Component without SRP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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