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

My jQuery Ajax seems to have a glitch, can someone help me figure out

Looking for some help with this HTML code: <section id="login"> <form> <input type="text" name="username" size="10" placeholder="username" /> <input type="password" name="password" size="10" placeholder="password" ...

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Removing a database record with JQuery

I have implemented a PHP function that converts any 2D PHP array into an HTML table. Within the table, I want to include a delete button in each row. When the user clicks on the delete button, I need jQuery to extract specific fields (3 fields) and submit ...

Why is it that the edit or delete button is not functioning when I attempt to click on the next page?

Having an issue with my script. It works fine for editing and deleting on the first page, but when I navigate to the next page, those functionalities stop working. Can anyone help me troubleshoot this problem? <script> $(function(){ $(&ap ...

What is the best method to ensure that none of the select option values are left empty?

I have a total of 5 select option drop down menus currently, but this number may increase in the future depending on requirements. The issue I'm facing is that when I select the last element, it returns true even though the other elements are empty. I ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Flip an image by analyzing the colors beneath it

Looking for a way to invert the color of specific areas under a mask (PNG) for a floating menu. Rather than inverting all at once, I want only certain parts to be inverted underneath the mask. Is this achievable, or is there another approach I should consi ...

What is the method to retrieve an object instead of a singular value upon selecting a v-select item?

My v-select component has an array of objects as its data source. Each object in the array contains two properties, one for the value and another for the text. I am trying to retrieve both values, not just the one specified for the value property. Is ther ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Ways to transition into a developer role

I'm currently studying Javascript and Dynamic HTML as part of a course, and while I'm not encountering any errors or warnings in Firefox and Chrome, I believe there might be some issues with my code. If anyone would be willing to take a look and ...

Showing a collection of cards within a dynamic container set up in a 3x3 grid layout to start

In an attempt to showcase cards within a responsive container utilizing bootstrap and django, my goal is to create a 3x3 grid layout on extra-large screens with scrollable overflow that adjusts based on device width. Initially, I experimented with wrapping ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Issues with the initial drop functionality in jQuery UI

How come the jQuery code does not work properly on the first drop? $(".drag").draggable({ revert: 'invalid', drag: function(event, ui) { $(this).addClass('valid'); } }); $("#droppable").droppable({ accept: '.valid&apos ...

Changing a particular field value within an array of objects in Angular 4

I have a scenario where I created a class called security: class security { public id:number; public name:string; } Next, I initialized an array of security objects: let s:security[]=[{id:1,name:'Alex'},{id:2,name:'John'},{id:3,nam ...

Ways to condense a text by using dots in the middle portion of it

How can I dynamically shorten the text within a container that varies in width? The goal is to replace the strings between the first and last words with dots so that it fits within the container. For example, Sydney - ... - Quito. It should only replace wh ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...