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

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

Enhance your Vue.js app with seamless page transitions using the

I am facing an issue and need some help. My goal is to create a web application-like interface. However, when I use vue.js transitions, it displays like this: https://i.sstatic.net/U1g6M.gif The transition automatically resizes, repeats, and changes si ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

The Socket.io Chat application is indicating a memory leak with the EventEmitter, detecting 11 listeners that have been added. To resolve this issue

My private chat application is built using socket.io, node.js, and MySQL. However, I encountered an error when trying to use socket.on('example', function(data){...});. The error code thrown is related to a possible EventEmitter memory leak with ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: If anyone has ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Is there a potential impact on performance when utilizing local variables instead of repeatedly accessing properties?

Examining JavaScript code optimized for a performance-sensitive environment, specifically a game engine in mobile settings. Oftentimes, this code avoids using local variables and instead relies on explicit chains, such as: if (this.x.y[z].i) { this.x ...

Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filte ...

Looking to adjust the width of a <div> element dynamically as the browser window resizes using jQuery

I am facing an issue where the width of a <div> should change based on the browser size using jQuery. Below is the code I have written for this functionality. if ($(window).width() > 990 && $(window).width() < 1190) { $("#greybor") ...

Key steps for effectively implementing a Substring-Filter on a JSON array in d3

Trying to apply filtering on a JSON data array structured like this: var data = [ { "key": "FirstGroup", "color": "#1f77b4", "values": [ { "label ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

v-for loop doesn't iterate over imported array

I am facing an issue with importing data from a file named clients.js into another file called clients.vue. My goal is to display the imported data in a table within the clients.vue file, but I am unable to access it after importing. Interestingly, if I c ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...

In a REST api, what is the appropriate response for a property that is missing a value?

Is it better for a property with no value assigned to be returned as null, or should the REST API skip such properties entirely? Let's consider a user object example with first_name and last_name. (In the below example, last_name is not necessarily a ...

Assistance required in translating Firebase syntax from version 7.15.1 to version 9.6.1

I'm embarking on my Firebase journey and trying to follow a tutorial that seems to be a bit outdated. I could use some assistance in updating the code to match the newer version, as it appears the syntax has changed. The tutorial uses Firebase 7.15.1, ...

Update dynamically generated CSS automatically

Is there a way to dynamically change the CSS? The problem I'm facing is that the CSS is generated by the framework itself, making it impossible for me to declare or modify it. Here's the scenario at runtime: I am looking to target the swiper-pa ...

Equal-Height Slide Deck Holder

I'm struggling to maintain a consistent height of 700px for my image slideshow, which consists of four images with varying heights. I attempted setting the img at max-height: 700px, but unfortunately that didn't yield the desired outcome. You ca ...

Every time I refresh the page, the user is automatically logged out

I am currently working on developing an admin dashboard using nextjs 13. I have encountered a specific issue where the user is redirected to the login page every time they reload the page. Upon inspecting in developer mode, I noticed that cookies are still ...

The file upload issue with FormData append in CodeIgniter is causing errors

My current challenge involves uploading files using AJAX to my CodeIgniter based website. Unfortunately, I am encountering an issue where I cannot retrieve the file field value in the controller. This results in an error message stating "Undefined index: & ...

Utilizing jQuery to scrape HTML and dynamically manipulate elements

Is there a way to retrieve HTML content from a different subdomain and incorporate it into the current site? HTML snippet: <head> <body> <div id = "items"> <div id = "#one"> <ul> <li><a href = "#">C ...