Created
September 27, 2021 10:44
-
-
Save sb-bilal-dev/1cddcd1234fed0b02946cba312920af4 to your computer and use it in GitHub Desktop.
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
/* | |
* Appying Separation of concenrns to React component. Separate logic out of Component using hooks. | |
*/ | |
const useSingleProduct = (productId) => { | |
const [product, setProduct] = useState(null); | |
const fetchProduct = async () => { | |
const res = await fetch(`https://api.example.com/products/${productId}`); | |
setProduct(res.json()); | |
}; | |
useEffect(() => { | |
fetchProduct(); | |
}, [productId]); | |
const currentPrice = useMemo(() => product?.discountPrice || product?.price, [product]); | |
const isOnSuperSale = useMemo(() => product?.discountPrice && product?.price - product.discountPrice > 100, [product]); | |
return { | |
product, | |
currentPrice, | |
isOnSuperSale, | |
}; | |
}; | |
const ProductPage = ({ productId }) => { | |
const [selectedVariantId, setSelectedVariantId] = useState(0); | |
const { | |
product, | |
currentPrice, | |
isOnSuperSale, | |
} = useSingleProduct(productId); | |
const { add: addToCart } = useCart(); | |
if (!product) return null; | |
return ( | |
<Container> | |
<Name>{product.name}</Name> | |
<Price>{currentPrice}</Price> | |
{isOnSuperSale && <SuperSaleBadge />} | |
<Description>{product.description}</Description> | |
<VariantSwitch | |
variants={product.variants} | |
selectedVariantId={selectedVariantId} | |
onVariantSelection={setSelectedVariantId} | |
/> | |
<Button onClick={addToCart}>Add to cart</Button> | |
</Container> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment