The created function in VueJS may sometimes result in an undefined outcome

I recently started a project with VueJs where I encountered an issue while making a GET request using the Axios library. The data was returned as expected, but I faced difficulties calling the loadUsers function inside mounted. Here is my code snippet:

export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then(function(response){
           helper.validation(response.data);
        });
     },
     loadUsers(){
        axios.get('/Thirdparty/loadUsers').then(function(data){
           this.users = data.data;
        });
     }
  },
  created(){
     let self=this
     self.loadUsers(); 
  }
}

Despite using the 'self' variable to call the loadUsers() function, I still encountered the error stating that 'this' is undefined.

Answer №1

When you reference this.users within the callback to axios.get().then() in the function loadUsers(), be mindful that using a standard function instead of an arrow function can cause unexpected behavior. In this case, this does not refer to the Vue instance as intended, leading to scope issues. To resolve this, either switch to an arrow function or adjust the way you reference this:

// Option 1 - Use an arrow function
export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then((response) => {
           helper.validation(response.data);
        });
     },
     loadUsers(){
        axios.get('/Thirdparty/loadUsers').then((data) => {
           this.users = data.data;
        });
     }
  },
  created(){
    this.loadUsers(); 
  }
}

// Option 2 - Adjust the reference
export default{
  data(){
     return {
        users : {}
     }
  },
  methods:{
     addCustomer(){
        var formData = $('#add-customer').serialize();
        axios.post('/Thirdparty', formData).then(function(response){
           helper.validation(response.data);
        });
     },
     loadUsers(){
        let self=this; 
        axios.get('/Thirdparty/loadUsers').then(function(data){
           self.users = data.data;
        });
     }
  },
  created(){
    this.loadUsers(); 
  }
}

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

Ways to retrieve the path of a button found within table cells

https://i.stack.imgur.com/pUYHZ.jpgI'm currently working on a table where I've created a button that's being used in various rows and tables based on certain conditions. There's a specific scenario where I need to display the button for ...

Concealing Social Security Numbers using AngularJS

I am currently working on masking SSN numbers using AngularJS. Expected Outcome: Before applying mask (onFocus) After applying mask (onBlur) Users are only allowed to enter numbers, and the SSN formatting is handled by filters. Below is a sample of the ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

The use of script src with vue.js is causing issues

I am looking to move my Vue code into an external .js file. Since I am new to Vue, I am trying to keep it simple without using webpack. However, I have encountered an issue where Vue does not work when using the script src tag in the html file. For instanc ...

Transforming JSON object to an array of arrays using JavaScript

Attempting to extract specific values from a JSON object and store them in an array can be quite tricky. Below is an example of what this process might look like: Example: var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]}, "2 ...

Using a Vue computed method to compare elements in two separate arrays

Presently, I am utilizing Vue v2.x.x and dealing with an array: sectionTitles = ['Technology', 'Data', 'Poverty and Research', ...] Additionally, I have jobsData structured like this: [{'title': 'Software Engin ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Creating an Angular project that functions as a library and integrating it into a JavaScript project: a step-by-step guide

Is it feasible to create an Angular library and integrate it into a JavaScript project in a similar manner as depicted in the image below? The project structure shows trading-vue.min.js being used as an Angular library. Can this be done this way or is th ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Working with JSON data in javascript

While trying to parse JSON data from a server, I came across a strange issue. The data consists of rows of data - essentially a list of lists - and it looks something like this: [[1,2,3],[4,5,6],[7,8,9]] When viewing the JSON data in FF (using Firebug), ...

Creating characters dynamically based on the length of user input in VSCode Snippet

Here is a simple vue-html snippet: { "BANNER1": { "prefix": "banner", "body": ["<!-- ----------------", "/// $1", "--------------------- -->"] } } This sni ...

Creating a Rails application that dynamically fills a table with data from a

Encountering an issue with Ruby on Rails. I have a "Host Model" that contains a method which has a longer runtime. class Host < ActiveRecord::Base def take-a-while # implement logic here end Attempting to access a page where this method ru ...

Enhance a query parameter in a Node.js application

When using Node.js / Express, I define a path and pass in a request and response. My goal is to always include a seed URL parameter when this path is accessed. Initially, I set the seed query param to 0 and redirect the URL. Next, I want to randomize tha ...