Dedicated to the Hydrogen framework, headless commerce, and building custom storefronts using the Storefront API.
Apologies if I'm displaying my ignorance, but I'm stuck on this currently. Creating my first headless Shopify store and I can't get my cartCreate mutation to work from the client side. It works from my backend, but receives a 405 Method Not Allowed response when sending my mutation from the client.
I was under the impression that the Storefront API is a public API and that all queries/mutations are POST requests, so it's not my request method and it isn't my permissions, right? I'm following other examples and they seem to make it work from the client side, so what am I doing wrong here?
Here's my mutation function:
export const addToCart = async (itemId, quantity) => {
const createCartMutation = gql`
mutation createCart($cartInput: CartInput) {
cartCreate(input: $cartInput) {
cart {
id
}
}
}
`;
const variables = {
cartInput: {
lines: [
{
quantity: parseInt(quantity),
merchandiseId: itemId,
},
],
},
};
try {
return await graphQLClient.request(createCartMutation, variables);
} catch (error) {
throw new Error(error);
}
};
And here's where I call it in my Add To Cart Button (React w/ Next.js):
const AddToCartBtn = ({ productId, quantity }) => {
const [ buttonText, setButtonText ] = useState('Add to Cart');
useEffect(() => {
console.log('add to cart', productId)
})
const handleAddToCart = async () => {
let cartId = sessionStorage.getItem("modSquidCartId");
console.log('cartId', cartId)
if (quantity > 0) {
if (cartId) {
await updateCart(cartId, productId, quantity);
} else {
let data = await addToCart(productId, quantity);
cartId = data.cartCreate.cart.id;
sessionStorage.setItem("modSquidCartId", cartId);
}
}
};
return <button onClick={handleAddToCart}>{buttonText}</button>;
};
Thanks for any and all help and guidance.
Solved! Go to the solution
This is an accepted solution.
SOLVED. I was messing up my environment variables. FALSE ALARM.
This is an accepted solution.
SOLVED. I was messing up my environment variables. FALSE ALARM.