Last active
May 16, 2024 07:43
-
-
Save maryojo/7740f3dbf1fae3371fd77fa38312aeff to your computer and use it in GitHub Desktop.
ProductCard with 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
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}/> | |
); | |
} |
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(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