medusa
medusa copied to clipboard
Cannot add an variant into a cart due to "missing price field"
Bug report
Describe the bug
I was trying to set up a shopping system for a site. Everything was working in the admin panel. I can pull products, I can create a cart. But when I want to add a variant to the cart, I get the error that there is no price even though there is. How can I solve this?
System information
Medusa version (including plugins): v1.20.6 Node.js version: v22.1.0 Database: PostgreSQL Operating system: Windows Browser (if relevant): Chrome
Steps to reproduce the behavior
- Create a item
- Create a variant
- Add price to variant
- In the code, try to add variant into card
- See error
Expected behavior
The variant is successfully added to the cart and prints the cart to the console
Screenshots
Code snippets
export default function PurchaseButton({
cart,
variant_id,
}: {
cart: Cart,
variant_id: string
}) {
const createLineItem = useCreateLineItem(cart?.id ?? localStorage.getItem("cart_id")!);
const addToCart = useCallback(() => {
createLineItem.mutate({
variant_id,
quantity: 1,
}, {
onSuccess: ({ cart }) => {
console.log('cart', cart);
}
})
}, [createLineItem, variant_id]);
// ...
}
"use client";
import { useProduct, useCart, useCreateLineItem, useGetCart } from 'medusa-react'
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation'
export default function ProductPage({
params: {
id
}
}: {
params: {
id: string
}
}) {
const router = useRouter();
const { cart, createCart } = useCart()
const { cart: fetchedCart } = useGetCart(localStorage.getItem("cart_id")!)
const { product, isLoading, isError } = useProduct(id);
const { status } = useSession();
useEffect(() => {
if (!isLoading && isError) {
router.push('/404');
}
}, [isLoading, isError, router]);
useEffect(() => {
console.log('status', status, cart)
if (status === 'authenticated' && !cart?.id) {
createCart.mutate(
{
}, // create an empty cart
{
onSuccess: ({ cart }) => {
localStorage.setItem("cart_id", cart.id)
}
}
)
}
}, [status]) // eslint-disable-line
return (
// ...
status === 'authenticated' ? (
(product?.variants?.[0].id! && fetchedCart) && <PurchaseButton
cart={fetchedCart as any}
variant_id={product?.variants?.[0].id!}
/>
// ...
)
}
Additional context
Add any other context about the problem here