Having trouble extracting data from a GET request in Vue.js and storing it in a variable?

My server is currently hosting a Vue.js app. When I enter http://localhost:9999/ into my browser, the browser fetches 4 crucial files: post.js, get.js, vue.js, and index.HTML containing the Vue code.

I have successfully implemented a dynamic ordered list where each list item includes buttons to add or remove elements, along with a debug button that logs variables to the console.

Now, I need to send a GET request to my server to retrieve an array of JSON data which will populate another ordered list.

I've attempted the following approaches without success:

//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
//inputData = get("http://localhost:9999/text/1")

The content of get.js looks like this:

// This file is correctly included in the vue.js index.HTML
//<script SRC="get.js"> </script>
function get(url, params) {
        // Return a new promise.
        return new Promise(function(resolve, reject) {
            // Perform XHR operations
            var req = new XMLHttpRequest();
            req.open('GET', url, true);
        req.setRequestHeader('Content-type', 'application/json');

            req.onload = function() {
                // Check for successful status
                if (req.status == 200) {
                    resolve(JSON.parse(req.response));
            }
            else {
                reject(req.statusText);
            }
        };

        // Handle network errors
        req.onerror = function() {
            reject("Network Error");
        };

        // Send the request
        req.send(params);
    });
}

Following the Vue.js method block, I call:

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    inputData = get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

Although the Promise contains the data, I'm unable to transfer it to the variable.

Promise {<pending>}
__proto__: Promise
catch: ƒ catch()
constructor: ƒ Promise()
finally: ƒ finally()
then: ƒ then()
Symbol(Symbol.toStringTag): "Promise"
__proto__: Object
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(4)
0: {text: "This List"}
1: {text: "was pulled"}
2: {text: "from the"}
3: {text: "server"}
length: 4
__proto__: Array(0)

To keep comments intact, I had to be creative:

@Apal Shah I appreciate your response. Your code appears cleaner than the then() alternative. Before reading your solution, I actually identified the issue through extensive console logging.

console.log('app.vueData prior assignment from inputData: ')
console.log(app.vueData)

app.vueData = inputData

console.log('inputData after assignment: ')
console.log(inputData)

console.log('JSON.stringify(inputData)')
console.log(JSON.stringify(inputData))

console.log(';)')

Console Output:

get block:
app.vueData prior assignment from inputData:
 [__ob__: Observer]
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
inputData after assignment:
 [__ob__: Observer]
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
 JSON.stringify(inputData)
 []
 ;)
https://github.com/vuejs/vue-devtools

 You are running Vue in development mode.
 Make sure to turn on production mode when deploying for production.
 See more tips at https://vuejs.org/guide/deployment.html

 (4) [{…}, {…}, {…}, {…}]
  0: {text: "This List"}
  1: {text: "was pulled"}
  2: {text: "from the"}
  3: {text: "server"}
  length: 4
  __proto__: Array(0)

Excited to test the solution now.

The corrected solution is as follows:

mounted() {
    this.$nextTick(async function () {

        console.log('get block: ')
        console.log('app.vueData before assigning from get() ')
        console.log(app.vueData)

        app.vueData = await get("http://localhost:9999/text/1")

        console.log('app.vueData after assignment: ')
        console.log(app.vueData)

        console.log('JSON.stringify(app.vueData)')
        console.log(JSON.stringify(app.vueData))
        })

        console.log(';)')
}

Note that the "async" keyword needed to be placed before the function declaration, not inside mounted() or this.$nextTick to work effectively.

Answer №1

The Promise you've created resolves the data once your HTTP request is complete, but your code doesn't wait for this resolution.

You have 2 options:
1. Use .then()
2. Use async/await (I prefer this because it looks cleaner)

If you choose to use async/await,

mounted() {
    this.$nextTick(async function () {
    var inputData=[]
    //get("http://localhost:9999/text/1", inputData)
    //get("http://localhost:9999/text/1").then(inputData)
    inputData = await get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

In the above code snippet, notice the async keyword before the function inside this.$nextTick, and the await keyword before calling your get method.

If you want to handle errors, you can utilize a try/catch block.

try {
  inputData = await get("http://localhost:9999/text/1");
} catch (e) {
  console.log(e);
}

If you prefer using .then(), your mounted method would look something like this:

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    get("http://localhost:9999/text/1").then(inputData => {
      app.vueData = inputData
      console.log(inputData)
      console.log(JSON.stringify(inputData))
    });
    console.log(';)')
    })
}

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

How to calculate the number of distinct elements using jQuery

Here is the HTML code I have: <input type="hidden" name="product_id" value = "1" class="product_id" /> <input type="hidden" name="product_id" value = "2" class="product_id" /> <input type="hidden" name="product_id" value = "5" class="produc ...

What is the best way to integrate a CSS file into Vue.js 2?

At the moment, I'm diving into Vue.js 2 but I've hit a roadblock. Can anyone advise me on how to incorporate external CSS in Vue.js 2? I would greatly appreciate any solutions you can offer. Thank you! ...

Parsing dates in Firefox using Moment.js and AngularJS

I'm currently incorporating Moment.js into my project and parsing a normal date string like "21-jun-2020". However, I've noticed that the parse result differs between Chrome and Firefox. _d: Mon Jun 21 2021 00:00:00 GMT+0530 (India Standard Time ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

Grab the webpage's URL by collecting the link from the src attribute of the script tag using XSLT

Can XSLT be used to extract a URL link specified within the src attribute of a script tag in an HTML file? Here is an example of the HTML file: <HTML> <BODY> <SCRIPT language="javascript" src="http://myspace.com" type="text/javascript"> ...

Unable to close the file upload window using Selenium

I've encountered a dilemma that I'm trying to solve. On my webpage, there's a screen that opens a dialog box for file upload. Although I managed to select the file, the dialog box refuses to close and remains open, preventing me from proceed ...

Emulating ArrowRight event using React Testing Library

I am facing a challenge with the React-Testing-Library. Within my application, I have two components called HeroesScreen and HeroesDiamondBar. The HeroesDiamondBar component is rendered inside the HeroesScreen component once the currentStep state variable ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Switching the Cursor Image When Hovering Over a Different Image with JavaScript or jQuery

I have been trying to implement a feature where I hover over an image and a custom cursor (150x150) appears. Despite my best efforts, the hover effect is not as smooth as I would like it to be. Can someone please provide guidance on how to achieve this sea ...

Is it possible to update my array using a put request?

I am having trouble updating the objects in my array and I need to be able to call them in Postman with a new value attached to the item I'm referencing. This is an assignment that is due today, so please help me. Check out this screenshot from Postm ...

The component fails to detect updates from the Vuex store

Check out this example that demonstrates the issue I'm currently dealing with: Here is the sequence of steps causing the problem: 1. Retrieve records from firebase 2. Update the state with the retrieved data 3. Render the component to display t ...

Discovering Worth within a Set of Embedded Arrays

I am currently in search of a solution for matching a value within an array of objects. My approach involves using the find method, which has been effective so far. However, I've encountered a scenario where I need to assign multiple values to a sing ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...

I am receiving an undefined response from Cheerio when attempting to fetch JSON data

My goal is to create a web scraper and I have successfully downloaded the HTML. Now, with this code snippet, I am attempting to extract the title from my HTML: fs.readFile(__filename.json , function (err, data) { if(err) throw err; const $ = cheerio.load ...

Is there a way to successfully deploy a Vue application within a subdirectory?

I have a complex build pipeline in place. It involves using a static site generator to build my website, which deploys to a "public" directory. The generated index.html file inside the "test" folder is where the app stub is located. Currently, the vue-cli ...

How can we develop a NodeJS function that returns a query result using a callback method?

I'm currently working on verifying the proper operation of a database using mocha/chai in NodeJS. I am looking for a solution to run a SQL query and then validate its execution. The issue I'm facing is that when I reach the assertion, the result ...

Tips for sending a spring form as a parameter in an Ajax request using a JavaScript function

I have a form in Spring with two buttons on a JSP file. <input type="button" onclick="saveFormActions(this.form)" class="btn primary publish border16" id="saveBtn" value="Save"/> <input type="submit" class="btn primary publish bor ...

Aligning my website in HTML

Is it possible for me to create a similar effect on my site like the one seen here ()? The site has a background with content layered on top of it. When you scroll the page horizontally, the content remains centered until you reach the very left edge, at w ...

Navigating with Vue2 router using various combinations of parameters, which may be unordered and

Is it possible to create a page displaying search results for various products with multiple filters such as size, weight, color, and country on the URL? I have managed to achieve some basic filtering using '?' in the URL structure (e.g: /color/ ...