Using VueJS to fetch and incorporate data into Vue components

After working on this VueJS code snippet with a successful fetch for jokes, I encountered an issue where the div intended to be populated was not displaying anything.

window.onload = function () {
    var app = new Vue({
      delimiters: ['[[', ']]'],
      el: '#app',
      data: {
        jokes: []
      }
    });

    function postdata(app){
        var initial_data = {'id': 1, 'model-name': 'Joke'}
        var self = this;
        fetch("\start-jokes\/", {
            body: JSON.stringify(initial_data),
            cache: 'no-cache', 
            credentials: 'same-origin', 
            headers: {
                'user-agent': 'Mozilla/4.0 MDN Example',
                'content-type': 'application/json'
            },
            method: 'POST',
            mode: 'cors', 
            redirect: 'follow',
            referrer: 'no-referrer',
            })
            .then(response => response.json()).then((json) => { console.log(json['jokes'])
                app.jokes.push(json['jokes'])
            })
    }

    postdata(app)
};

The response jokes is structured as an Array of dictionaries with key-value pairs like key, text, and name.

https://i.sstatic.net/2dstd.png

Upon closer inspection and logging in the console (image sourced from the network tab in inspect element), it appears that nothing is being populated.

https://i.sstatic.net/z4KOk.png

Each element in the dictionary contains a get and set property which seems to be reactive. The challenge now is how to convert it into JSON format.

Despite trying to log app.jokes in the console, the result returned was undefined.

Answer №1

implementing Vue methods within the DOM

new Vue({
    el: '#app',
    data: {
      title: '',
      message: ''
    },
    mounted: function() {
      this.fetchData()
    },
    methods: {
        fetchData(){
            var initial_data = {'id': 1, 'model-name': 'Joke'}
            var self = this;
            fetch("\start-jokes\/", {
                body: JSON.stringify(initial_data),
                cache: 'no-cache', 
                credentials: 'same-origin', 
                headers: {
                    'user-agent': 'Mozilla/4.0 MDN Example',
                    'content-type': 'application/json'
                },
                method: 'POST',
                mode: 'cors', 
                redirect: 'follow',
                referrer: 'no-referrer',
                })
                .then(response => response.json()).then((json) => { console.log(json['jokes'])
                    this.jokes.push(json['jokes'])
                })
        }
    }
  })

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

Creating a basic "hello world" application in Vue Native

I have set up a new app and got it up and running on the Android emulator by using the following commands: npm install -g vue-native-cli vue-native init test1 // Creates a new CRNA project cd test1 npm start When I go to http://localhost:19002/ and clic ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

What is the best way to implement an effect based on the movement or position of the mouse?

I have 3 buttons positioned absolutely: .micro { position:absolute; } #micro_1 { left:1165px; top:176px; } #micro_2 { left:800px; top:300px; } #micro_3 { left:300px; top:400px; } I am looking to create a fading effect on these 3 elements based on the ...

Discover the best practices for integrating Vuex with Veulidate in Vue 2 to ensure optimal usage

Within the code snippet below, I am utilizing two methods on input to update both state and apply vuelidate validation rules. Unfortunately, the validation rules are not being applied properly as $v.newEmloyeeName.$dirty always returns true. How can I re ...

Disallow the user from resizing the inner Div beyond the boundaries of the parent Div in Angular Resize Event

Is there a way to restrict the resizing of the inner Div in the example so that it stays within the boundaries of the Outer Div? I am utilizing angular-resize-event. https://www.npmjs.com/package/angular-resize-event Check out the demo on Stackblitz: htt ...

How to bind parent object scope to MySQL query's anonymous callback in Node.js

As a newcomer to node.js, I am still working on understanding the concept of scoping anonymous functions. I have created an object with multiple methods and within one of my methods, I retrieve a MySQL connection from a pool and then execute a query on tha ...

Having trouble with updating data in MongoDB using Node.js

I am currently in the process of developing a multiplayer game, complete with a login system. I've encountered some issues when trying to update the user ratings using db.collection.update(). Strangely, whenever I input the username of a player, it re ...

Issue with changing color of intersectObjects in Three.js not being properly registered [example code in jsfiddle]

I'm encountering an issue where I can't seem to change the color of a cube when someone hovers over it. I've simplified the code as much as possible. Click here for the code <script> var container; var scene, camera, renderer, mouse, ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

Error retrieving property in Internet Explorer when using AJAX

Encountering error message Unable to get property ‘replace’ of undefined or null reference on line var ajax_html = $(xml).find("#search-ajax-content").html(); while utilizing AJAX in IE (specifically testing with IE11). This code operates without any g ...

What is the best method for including parameters in OBJECT_URL when sharing a post on Facebook?

Regarding this line: FB.api('/me/namespace:read' + '?article=http://www.xxxxxxxxxxxxxx/tm/redir.php&access_token=','post', Whenever I attempt: I encounter errors. How can I successfully pass parameters in the OBJECT_UR ...

Styling HTML elements with CSS to create a full width underline effect

Is there a way to make the underlines/borders full width for each line in a paragraph without adding line breaks? I'm seeking suggestions on how to achieve this. Two potential solutions I've considered are using the tag or creating an image, ...

Tips for properly formatting objects in a JSON file with commas using nodejs

I have a client-server setup where I am sending right click coordinates from the client side to the server side and storing them in a JSON file. Each coordinate is stored as a separate object in the JSON file. This is an example of how my JSON file looks: ...

Trouble getting data in ag grid when initialized with Vue and axios

I'm facing a peculiar issue where data retrieved from mongoDB using axios is not displaying on the grid. Despite confirming that the data has been successfully loaded into the view (tested it already), it seems to be missing within the beforeMount, mo ...

When using the Vue Array.splice() method, the DOM element is not removed in the element-ui table

I am facing an issue with a table containing hierarchical data in Vue. When attempting to remove a child using "array.splice", the DOM structure does not update reactively. Has anyone encountered this before? Are there any potential solutions? This proble ...

Exploring the world of array initialization in Javascript

function calculateAverage() { var total = 0; var arr = []; while (true) { var input = Number(prompt("Please enter a value")); if (input !== 0) { arr.push(input); total = arr.reduce( (accumulator, currentValue) => accumu ...

Converting PHP backreferencing to JS regular expression translation

I need to convert this code into JavaScript: $formateTweet = preg_replace("/http([^ ]*)/", "<a target=\"_blank\" href=\"http\\1\">http\\1</a>", $formateTweet); $formateTweet = p ...

Submit the request when the fileReader's onload event is triggered

Do you have any suggestions on how to improve my fileReader for uploading images? I am currently facing an issue where multiple requests are being sent to the server when there are more than 1 image due to a for loop. How can I modify my code to address ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

Employing the Quasar q-select feature with an active filter on a JSON object for its options

I'm having trouble finding examples using the composition API for this scenario and could really use some guidance. I have a q-select component that passes options as a prop through an axios request. The data is structured like this: [{description: "A ...