Skip to content

Instantly share code, notes, and snippets.

@AkyunaAkish
Last active April 18, 2024 04:35
Show Gist options
  • Save AkyunaAkish/38c7b2ecd706e6426691cba85bd2fc1c to your computer and use it in GitHub Desktop.
Save AkyunaAkish/38c7b2ecd706e6426691cba85bd2fc1c to your computer and use it in GitHub Desktop.
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