Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div.

Here is my VueJS setup:

var example = new Vue({
  el: '#example',
    data: function () {
        return {
            list: []
        }
    },

  methods: {
    fetchMovies: function (city) {
        $.getJSON('api/city?city=' + city, function(tasks) {
            console.log(tasks); // Response from API
            console.log(city); // Data sent by button
            this.list = tasks; // Assign API results to list array
            this.todos.push(this.newTodoText); // Push results to div
        }.bind(this))
    }
  }
});

Below is the button and template structure:

<div id="example">
  <button v-on:click="fetchMovies('stockholm')">Greet</button>
</div>

<div id="exampleList">
    <tasks></tasks>
</div>

<template id="tasks-template">
    <div>
        <h1>vue grjer!</h1>
        <ul class="list-group">
            @{{ list.name }}
                <li class="list-group-item" v-model="newTodoText" v-for="task in list.data">
                    @{{ task}}
                </li>
        </ul>
    </div>
</template>

Within chrome dev tools, I can view both log(city) and log(tasks). The API results are being retrieved successfully. However, struggling to push it to the template. An error occurs stating

TypeError: undefined is not an object (evaluating 'this.todos.push')

Answer №1

When you are inside the success callback of your $.getJSON function, keep in mind that this no longer refers to your Vue instance. To avoid confusion, it's best practice to save a reference to your view before making the $.getJSON call:

var vm = this;
$.getJSON(..., function(tasks) {
    ...
    vm.todos.push(...)

Alternatively, you can explore using vue-resource. This library supports the Promise API and automatically binds the Vue instance inside callbacks, allowing you to still reference this. Plus, it's much lighter than relying on jQuery.

Answer №2

When working with the data property in Vue.js, it is important to provide default values for variables such as todos and newTodoText. This can be achieved by setting them to empty arrays or strings like so:

data: function () {
    return {
        list: [],
        todos: [],
        newTodoText: ''
    }
},

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 cookies in R Shiny: Storing variables for future use

Writing a fixed string to cookies can be done easily using methods like Cookies.set(\'cookie_2\', \'value\', { expires: 7 }) (see tutorial here). However, saving the variable user to cookie_2 may require a different ...

Creating subdocuments with input types in MERN stack using Apollo Sandbox and MongoDB mutations

These questions are specific to a Node server application built in JavaScript using express, apollo-server-express, mongoose, and graphql. Below is the content of the package.json file: { "name": "dimond-media-mern-app", "vers ...

Implement a jQuery slideshow with a full background image, aiming to set up a clickable link on the final image of the

Could someone please help me with a query I have regarding a background image slide show using jQuery code? I have set up a slide show with multiple images and would like to make the last image clickable. Is it possible to achieve this specific functionali ...

Incomplete JSON stringification

Could someone provide insight into the reason behind this behavior? let data = JSON let date = '10-7' data['id'] = [] data['id'][date] = [[1,2,3]] data['id'][date].push([1,1,1]) console.log(data) // Outputs: { i ...

Obtain the value of the input

I need assistance with the input below: <input value="25" data-hidden-value="25" name="associations[agencies][ids][]" data-hidden-name="associations[agencies][ids][]" class="string" type="hidden"> This particular input is generated dyna ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

What is the best way to attach a function to an href attribute for creating a dynamic link?

I've been struggling to pass a function to the href attribute in my link tag, but no matter what I try, it just doesn't seem to work. It either redirects to a 404 page or is completely unclickable. What could be causing this issue? This link app ...

How can I prevent the browser's back button from functioning on an AngularJS webpage?

Is there a way to disable the browser's back button and refresh button in Angular? For example, in my source code: Page Source: "use strict"; .controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) { $scope.$on ...

Adjust the background of the page at regular intervals

I currently have: <script type='text/javascript'> var imageID=0; function changeimage(every_seconds){ //change the image if(!imageID){ document.getByTagName("body").src="icwXI.jpg"; imageID++; } else{if(imageID==1){ document.ge ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Instructions on adjusting the image size within a MUI Card

import { Card, CardActionArea, CardContent, CardMedia, Typography, } from "@mui/material"; import React from "react"; import { styled } from "@mui/material/styles"; const CardImage = styled("div")(({ theme ...

Two values are returned from the Node.js Mongoose Exports function

Currently, I am encountering an issue with my project where a service I developed is up and running. However, it is not providing the desired value as a response. Specifically, the goal is to generate coffee items linked to specific companies. Whenever new ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Performing a reverse image search request using Javascript/AJAX to query Google

I have been attempting to perform a reverse image search request using AJAX, but I keep receiving 302 errors. After checking the Firebug console, I discovered that the response header from Google contains a URL linking me to the results. However, I am unsu ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

Perform a JSON query using JavaScript

Is there a way to query JSON using JavaScript? In my JavaScript code, I have a JSON stored in a variable called 'json'. This JSON is an array of data, each containing 3 attributes: 'name', 'city', and 'age'. I am in ...

Retrieve JSON data from a RESTful API by utilizing pure javascript

I'm eager to try out the Wikipedia search API in JavaScript, even though it might be simpler with jQuery. I want to make sure I understand the basics first before turning to frameworks. Below is the code I've come up with, but for some reason, I ...