The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method.

This is what I have:

export default {

  data () {
    return {
      types: null
    }
  }, 

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      });
  }
}

However, I am encountering the following error in the console:

 Cannot set property 'types' of undefined(…)

Interestingly, when I log like this:

 ready () {
   TypeService.showAll(1)
      .then(function(data) {
          console.log(data);
      });
  }

The data is not empty!?!?

https://i.stack.imgur.com/mWG2V.png

I am puzzled by this situation. It's frustrating me.

--EDIT--

TypeService.showAll(1)  
         .then(({ data }) => ({
            this.types: data.types
          }.bind(this)));

Answer №1

The error lies in this.types, rather than data.types (which might not be explicitly mentioned in the JavaScript error message).

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      });
  }

Within the function, this does not refer to what you may expect (it is not referring to the Vue component). To resolve this issue, try the following:

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      }.bind(this));
  }

Answer №2

Give it a shot

initialize () {
let _that = this
CategoryService.displayAll(1)
  .then(function(results) {
      _that.categories = results.categories
  });
}

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 retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

Utilizing a While Loop for SQL Queries in a Node.js Environment

So, I was attempting to iterate through an array using a while loop. I was able to successfully print a result from the SQL connection without the while loop, confirming that the query is working. However, when I tried to implement the same query within a ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

How should we structure our JavaScript code: MVC or self-rendering components?

I'm in the process of developing a highly JS-centric web application. The bulk of the work is being carried out on the client side, with occasional syncing to the server using AJAX and XMPP. This is my first venture into creating something of this ma ...

The addClass and removeClass functions seem to be malfunctioning

Hey everyone, this is my first time reaching out for help here. I looked through previous questions but couldn't find anything similar to my issue. I'm currently working on a corporate website using bootstrap3 in Brackets. I've been testing ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Tips for using multiple Angular directive modules in PprodWant to enhance your Pprod experience by

Currently, I am working on jhipster Release 0.7.0 and our jhipster app has multiple types of directive modules – one for the index page and another for common directives. However, when we run the app on Prod profile, an exception occurs: [31mPhantomJ ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Insert icons in the action columns and in every single row

https://i.stack.imgur.com/4EH91.png In the realm of vue.js, there exists a project tailored for a thriving car sales company. The intricacies lie within a table fuelled with essential information concerning each vehicle, evident in the image provided. Ever ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...

Please provide instructions on how to submit a POST request to the API using Restangular

I'm currently utilizing the Django REST framework to write APIs. It functions properly when data is manually entered on this page: http://example.com/en/api/v1/add_comment/ views.py (API) class AddComment(generics.CreateAPIView): """ Creating a new ...

extract information from an external JSON document

I have a JSON file filled with data, along with a JSX file containing a button and a div. I'm looking to extract the data from the JSON file and display it in the div when the button is clicked. However, I'm at a loss on how to achieve this. The ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

Transferring data from a stream in NodeJS to FrontEnd using ReactJS

How are you doing? I'm trying to figure out how to send a large data request from PostgreSQL to the FrontEnd in JSON format. Can anyone help with an example of how this can be achieved? Thank you. Here is my code: const express = require('expr ...