Fetch the Cart Id from the JSON response

I am working on capturing the cartID in a JavaScript variable from a JSON response.

Here is the code I have so far that requests the cart information:

function getCart(url) {
   return fetch(url, {
       method: "GET",
       credentials: "same-origin"
   })
   .then(response => response.json())
};

var cartID = 'unknown';

getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));

The data logged in the console looks like this:

Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd0d8fddavalue="">[email protected]</a>", ................. }]

I've attempted different methods to capture the cart ID into the variable cartID, but it always shows as 'unknown' and is logged before the data response.

Do you have any suggestions on how to delay until the response is ready and then assign 'cartID' with the id value?

Answer №1

To extract the cartID from a JSON array response, you can utilize a loop to iterate over each cart object.

function fetchCartID(apiURL) {
    return fetch(apiURL, {
        method: 'GET',
        credentials: 'same-origin'
    })
    .then(response => response.json())
 };
 
 var cartIdentifier = 'unknown';
 
 fetchCartID('/api/storefront/carts')
 .then(
     data => {
         // The response consists of an array of cart objects. Extracting the ID from the first cart
         cartIdentifier = data[0].id;

         // Alternatively, looping through the response to extract the ID from each cart object
         for (var i = 0; i < data.length; i++) {
             cartIdentifier = data[i].id;
         }
     }
     )
 .catch(error => console.error(error));

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

Guide on how to return a JSON result as a Dictionary instead of an Array using Express.js

I need to format my response as a dictionary with specific key-value pairs, like so: { "id": 5928101, "category": "animal welfare", "organizer": "Adam", "title": "Cat Cabaret& ...

The issue of JQuery and document ready being triggered multiple times while loading data into a control

Ever since implementing the load function to load content into a DIV upon document ready, I've noticed that all associated functions are firing multiple times (often twice, and sometimes endlessly). The scripts included in the head tag of all pages a ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Issue with deploying NEXT.JS due to a failure in the build process caused by next lint

Issue I have been encountering deployment failures on Vercel due to lint errors in test files within my git repository. Despite following the recommendations from the Vercel documentation for ESLint settings, the issue persists. According to Vercel' ...

What's the best way to apply a margin top to an image using Tailwind CSS?

Is there a way to adjust the top margin of an image in Tailwind CSS? I'm having trouble making my logo clearly visible and think giving it some space at the top might help. How can I do this within the Tailwind CSS framework? https://i.sstatic.net/Ae ...

Tips for navigating a dynamic viewport using scroll movement

Attempting to create a responsive page with two distinct sections at this example link including: Map View Table View Both of these views (table and map divs) need to be responsive without a hard-coded height, so the size of the map div adjusts automatic ...

Is there a way to prevent the onClick event from executing for a particular element in React?

Currently working with Material UI, I have a TableRow element with an onClick event. However, I now need to incorporate a checkbox within the table. The checkbox is enclosed in a TableCell element, which is nested within the TableRow. The issue arises wh ...

What is the process for uploading a JSON object containing an image to a server?

Here is the code I am using to send data to the server in JSON format: NSData *jsonData = [dict dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *jsonLength = [NSString stringWithFormat:@"%d",[jsonData length]]; //I ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

NgFor is failing to display data from a fully populated array of objects

CLICK HERE FOR THE IMAGE So, let's tackle the issue at hand. I have an array that contains data fetched from an API. These data points are essentially messages. Now, below is the TypeScript file for a component where I aim to display all these messag ...

(WebApi) Unable to convert a collection of objects to Json serialization

I have encountered an issue with serializing and returning a collection of objects from a WebApi controller. Although it works fine for single object serialization, it fails when the method tries to serialize a collection of these objects. Here is an exam ...

Validation of Numbers and Characters in DevExpress ASP.NET TextBox

When I try to use masking on the textbox for credit card format, I am having trouble entering a hyphen. It seems that the validation does not accept dashes as I only checked for numbers. Any help would be appreciated. Thank you. <script> functio ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Every time I input information into the form, it keeps coming back as undefined

function displayProduct() { var product = document.getElementById("productForm"); var item = product.elements["item"].value ; document.getElementById("outputResult").innerHTML = item ; } <div> <p id="outputResult"></p> </di ...

Using ReactJS to insert an array of objects into an object nested within another array object

After receiving a response from a REST call, I am working with an array of objects. response.data.steps Here is an example of how it looks: https://i.sstatic.net/h2QsL.png Now, my task is to add a new Object Array to each Child of this array. Can anyo ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Event handlers in JQuery are not connected through breadcrumb links

Wondering how to ensure that the click handler is always attached in my Rails 4.1 app where I am using JQuery-ujs to update cells in a table within the comments#index view. In my comments.js.coffee file, I have the following code snippet: jQuery -> ...

Connect CSS Transition to a click action

Below is the code snippet. When you click on the div, it creates a folding effect to the left. You can view it here. I want to link this effect to the arrows I use for sliding back and forth. For example: The left arrow should move the slide to the l ...

Leveraging the power of a three.js canvas in conjunction with Custombox

I am currently using three.js to generate a 360 panorama on my webpage. I have a collection of thumbnails displayed on the page, and when a thumbnail is clicked, two actions take place. The correct texture is swapped into the panorama canvas (which is fu ...

In Python, when using the json.loads function, you may encounter a <class 'exceptions.ValueError'> error message like this: "Expecting property name: line 1 column 3 (char 2

Currently, I'm developing a python CGI script that is meant to receive a JSON string as input and process it accordingly. However, during testing, I keep encountering ValueErrors, and the cause behind them remains unclear to me. Here's an exampl ...