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

Tips for preventing the ng-click event of a table row from being triggered when you specifically want to activate the ng-click event of a checkbox

So, I've got this situation where when clicking on a Table Row, it opens a modal thanks to ng-click. <tr ng-repeat="cpPortfolioItem in cpPortfolioTitles" ng-click="viewIndividualDetailsByTitle(cpPortfolioItem)"> But now, there&apos ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Troubleshooting the 'npm ERR! ERESOLVE could not resolve' and 'peer dependency' issues: A guide to fixing the ERESOLVE error in npm

After several days of encountering an error while trying to set up a website for remote training, I have not been able to find a solution that fits my needs. Requesting your help to resolve the issue and get the site live on Vercel. Thank you in advance f ...

JSPM encountered an issue with installation from GitHub (404 error), but it is able to successfully install packages from npm

I am encountering a frustrating issue with my Package.json file for a GitHub repository in my organization. Attempting to pull it in via jspm is causing errors. { "name": "tf-modernizr", "version": "1.0.0", "description": "", "main": "modernizr.js ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

What is the process for integrating npm packages with bower?

Currently, I am immersing myself in the realm of ember using a grunt/bower workflow. I have noticed that a lot of the ember extensions are available on github as npm packages. Can anyone provide guidance on the most effective approach for incorporating th ...

What is the process for programmatically importing a module into the local scope in Node.js?

The coding environment is using a browser and the bundle tool being used is webpack. In my router.js file, I have the following code: import foo from './views/foo.vue' import bar from './views/bar.vue' import zoo from './views/zoo. ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Executing Nuxt middleware on the client-side post static rendering

We are transitioning from using a Single Page Application to statically generated pages, but we are encountering an issue with middleware. Essentially, when Nuxt is statically rendered, the middleware runs on the build server first and then runs again aft ...

Tips for eliminating unnecessary data in written content

Could anyone provide a recommended method for removing unnecessary symbols from text strings? For instance, transforming "CWC%20-%20Maint%20Eng%20-%20El" into the more readable format of "CWC - Maint Eng - El". ...

Is there a way to verify the functionality of DigitalOcean features using doctl before transitioning to a live environment?

As a newcomer to using DigitalOcean Functions, I have set up some JavaScript namespaces using the doctl serverless command. My main query is regarding testing DigitalOcean functions locally before deploying them to production. Is there a way to do this wit ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Autonomous JQuery Modules

Is it possible to separate the functions in JQuery and use only the ones needed by splitting the file with PHP? By doing this, I aim to improve page speed, save bandwidth, and have more control over the functions used through the backend. Can the functio ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...