Last active
April 18, 2024 04:35
-
-
Save AkyunaAkish/38c7b2ecd706e6426691cba85bd2fc1c 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
type Product = { | |
// ... product stuff | |
quantity?: number; // add this to the existing product type | |
} | |
// create new state (and add it to the types and context value etc) | |
const [populatedCart, setPopulatedCart] = useState<Product[]>([]); | |
async function fetchProduct(productId: string): Promise<Product> { | |
const res = await fetch(`${BASE_URL}/products/${productId}`); | |
if (!res.ok) { | |
throw new Error(`Error fetching product ${productId}: ${res.statusText}`); | |
} | |
const productData = await res.json(); | |
return productData as Product; // Type assertion might still be needed depending on data structure | |
} | |
const populateCart = async () => { | |
try { | |
const productsWithQuantity: Product[] = []; | |
for (const productId in cart) { | |
const product = await fetchProduct(productId); | |
product.quantity = cart[productId]; | |
productsWithQuantity.push(product); | |
} | |
setPopulatedCart(productsWithQuantity); | |
} catch (error) { | |
// ... error handling | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment