Issue with NextJs function not receiving the specified argument variable

Currently, I am focused on developing a Shopify website and fine-tuning the functionality of the shopping cart. My onClick event triggers a function that initiates the process of adding items to the cart. The first step involves checking if there is an existing cartId stored in local storage. If not, a new cart is generated through a call which successfully returns with a newly generated id. This id is then stored in local storage and assigned to a local variable as the cartId by retrieving it using localStorage.getItem('cartId'). Subsequently, the addItemToCart function is invoked. However, upon inspecting the console.log output within that function, only the itemId and quantity values are passed correctly while the expected cartId appears as undefined. Despite confirming the accuracy of the locally stored variable multiple times, the correct value fails to be passed through.

This function is triggered from the onClick() event

async function addToCart(itemId, quantity) {

    console.trace();

    // Verify if a cartId was provided, if not make a request to create a new cart before adding the item
    if (localStorage.getItem('cartId') === null) {

        console.log('------------------------------')
        console.log('Creating new cart with item...')
        console.log('------------------------------')

        const shopifyResponse = await createCart();

        localStorage.setItem('checkoutUrl', shopifyResponse.checkoutUrl)
        localStorage.setItem('cartId', shopifyResponse.cartId)

    }
    let savedCartId = localStorage.getItem('cartId') 


    console.log('--------------------------------')
    console.log(`Adding items to existing cart: ID: ${savedCartId} ...`)
    console.log('--------------------------------')

      const shopifyResponse = await addItemToCart({
        itemId,
        savedCartId,
        quantity
      })
      
      console.log(shopifyResponse)
}

The addItemToCart function intended to receive the cartId

import { postToShopify } from "./shopify";

export const addItemToCart = async ({  itemId, cartId, quantity }) => {

    console.log(`Item Id: ${itemId}`)
    console.log(`Cart Id: ${cartId}`) //Returns undefined no matter where I have the argument in the function
    console.log(`Quantity: ${quantity}`)

    try {
      const shopifyResponse = await postToShopify({
        query: `
          mutation addItemToCart($cartId: ID!, $lines: [CartLineInput!]!) {
            cartLinesAdd(cartId: $cartId, lines: $lines) {
              cart {
                id
                lines(first: 10) {
                  edges {
                    node {
                      id
                      quantity
                      merchandise {
                        ... on ProductVariant {
                          id
                          title
                          priceV2 {
                            amount
                            currencyCode
                          }
                          product {
                            title
                            handle
                          }
                        }
                      }
                    }
                  }
                }
                estimatedCost {
                  totalAmount {
                    amount
                    currencyCode
                  }
                  subtotalAmount {
                    amount
                    currencyCode
                  }
                  totalTaxAmount {
                    amount
                    currencyCode
                  }
                  totalDutyAmount {
                    amount
                    currencyCode
                  }
                }
              }
            }
          }
        `,
        variables: {
            cartId,
          lines: [
            {
              merchandiseId: itemId,
              quantity,
            },
          ],
        },
      });
  
      return shopifyResponse;
    } catch (error) {
      console.log(error);
    }
  };

Answer №1

addToCartFunction requires an object as input with the properties: productID, cartID, and amount. These parameters need to be destructured.

When you invoke this function in updateCart, make sure that the object passed contains the property currentCartID instead of cartID. Here's how you can correct it:

const response = await addToCartFunction({
  productID,
  cartID: currentCartID,
  amount
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to delete scheduled tasks in BreeJS

I am currently working on an express server that initiates a recurring job upon client request for a specific duration. The challenge I am encountering is figuring out how to stop and remove that particular job once it has been completed. The following is ...

When using Intl.DateTimeFormat, unexpected output may occur when formatting dates prior to the year 1847

Why do dates before 1848 result in May 10 when formatted? Could this be related to time zones? And if so, how can I prevent this issue when creating a date object from an ISO date string like YYYY-MM-DD format? (Tested on Chrome 59) const workingDate ...

What is the most effective way to redirect users accessing from Android devices?

Attempting to send all Android users to a designated page. I attempted this method using php, but uncertain of its reliability. Need assurance that it will work for all possible Android devices. Thoughts on the safety of this approach? <?php $user_ag ...

Ways to verify if a specific email and name are already present in MongoDB

I need to check if a selected user's email and name already exist in my MongoDB database. I want to ensure that both the email and name are unique, without any duplicates of these values. Although I have functional code for this task, I am curious if ...

Accessing the $index value from the selected option when using ng-change within a select element

Although there are similar questions out there, I couldn't find one that addresses my specific need: ngRepeat inside option-tag ngChange inside select-tag I am trying to retrieve the index of the selected option. Here is a snippet of my code: < ...

Implementing React selectors to manage the state changes on page load and when a user

I'm currently delving into React selectors with ReSelect, and while things seem to be going well, I have a feeling that there may be an issue in my logic. 1 - Upon receiving an AJAX response, I obtain a list of "categories" consisting of id, name, an ...

Reset the checked state in React JSX to false by using a reset button

After attempting to reset selected radio buttons on this list, it seems like the change I made from {checked} to {user.checked} in input check is causing issues. This modification can be traced back to UserListElement.tsx In an effort to resolve this issu ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

How can you transform a nested array into a flat JavaScript map?

If we consider a JavaScript Map structured like this: [ { id: 1, name: "Foo", contents: [1,2,3], morecontents: ["a","b"], }, { id: 2, name: "Bar", c ...

Send live information to router-link

I'm struggling to pass a dynamic path to vue-router, but I can't seem to get the syntax right. Here's what I've been attempting: <li v-on:click="$emit('closeDropdown')"><router-link :to="item.route" id="button">{{ ...

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

Exploring the functionality of using getStaticProps in conjunction with the next-redux

I am currently in the process of developing a straightforward next.js application. To manage state, I have opted for next-redux-wrapper. In the main page of my app, I aim to retrieve all the rooms stored in my database via my API using store.dispatch. Uti ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...