I am implementing a feature using NextJS and the Shopify Storefront API, specifically working with cart mutations.
In src/hooks/cart/useAddCart.ts, I have defined hooks for adding products to the cart.
If there is no cart ID, I execute createCart() and add the cart ID to local storage.
If a cart ID exists in local storage, my intention is to use it to add products with addToCart().
However, when I checked console.log(addToCartResponse.data.cartLinesAdd.cart.id),
I found that the ID returned was not the cart ID existing in local storage, as shown below.
Please advise on how to add products to the cart using the cart ID that exists in local storage.
(src/hooks/cart/useAddCart.ts)
import { useMutation } from '@apollo/client'
import {
CREATE_CART_MUTATION,
ADD_TO_CART_MUTATION,
} from '@/graphql/mutations/cart'
import { Result, Ok, Err } from 'oxide.ts'
import { CartError, CartErrorEnum } from '@/const/cart'
export const useAddCart = (productVariantId: string) => {
const [createCart] = useMutation(CREATE_CART_MUTATION)
const [addToCart] = useMutation(ADD_TO_CART_MUTATION)
const handleAddToCart = async (
quantity: number,
): Promise<Result<undefined, CartError>> => {
let cartId = localStorage.getItem('cartId') ?? ''
if (!cartId) {
try {
const response = await createCart()
if (response.data && response.data.cartCreate) {
cartId = response.data.cartCreate.cart.id
localStorage.setItem('cartId', cartId)
}
} catch (error) {
return Err(CartErrorEnum.addToCartFailure)
}
}
try {
const lines = [
{
quantity: quantity,
merchandiseId: productVariantId,
},
]
console.log(cartId)
// cartId: gid://shopify/Cart/c1-011f596002781b30443f9e29b449e52d
const addToCartResponse = await addToCart({
variables: { cartId, lines },
})
console.log(addToCartResponse.data.cartLinesAdd.cart.id) // gid://shopify/Cart/c1-fc44819d7ce6c6cfd8cd292b253a629d
if (addToCartResponse.data && addToCartResponse.data.cartLinesAdd) {
return Ok(undefined)
}
} catch (error) {
console.error('failed error', error)
return Err(CartErrorEnum.addProductFailure)
}
return Err(CartErrorEnum.unknownError)
}
return { handleAddToCart }
}
(src/graphql/mutations/cart.ts)
import { gql } from '@apollo/client'
export const CREATE_CART_MUTATION = gql`
mutation {
cartCreate(
input: {
lines: [
{
quantity: 2
merchandiseId: "gid://shopify/ProductVariant/45756804596016"
}
]
attributes: { key: "cart_attribute", value: "This is a cart attribute" }
}
) {
cart {
id
createdAt
updatedAt
lines(first: 10) {
edges {
node {
id
merchandise {
... on ProductVariant {
id
}
}
}
}
}
}
}
}
`
export const ADD_TO_CART_MUTATION = gql`
mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
id
lines(first: 10) {
edges {
node {
id
merchandise {
... on ProductVariant {
id
}
}
}
}
}
}
}
}
`