When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is.

Here is my class:

export default {
    name: "Contact",
    components: {
        FooterComponent: FooterComponent,
        NavigationComponent: NavigationComponent
    },
    data() {
        return {
            locale: Cookie.get('locale'),
            nameAndLastName: '',
            email: '',
            subject: '',
            message: '',
            showPopUp: false
        }
    },
    methods: {
        sendEmail(e) {
            e.preventDefault();
            this.$validator.validateAll();
            if (!this.$validator.errors.any()) {
                let params = new URLSearchParams();
                params.append('nameAndLastName', this.nameAndLastName);
                params.append('email', this.email);
                params.append('subject', this.subject);
                params.append('message', this.message);

                axios.post(this.$apiUrl + `rest/api/public/Contact/contact`, params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(function (response) {
                        if (response.statusText === 'OK') {
                            console.log(this.showPopUp);
                            this.showPopUp = true;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        // This throws error TypeError: Cannot read property 'showPopUp' of undefined

                    });
            }
        }
    },
    mounted: function () {
        console.log('test');
        console.log(this.showPopUp);
    },
}

My issue arises when attempting to send a message. Although the response indicates success, and the email is sent, I continue to encounter the error

TypeError: Cannot read property 'showPopUp' of undefined
... When I try to print console.log(this.showPopUp) in the mounted hook, the variable displays correctly. So why am I unable to access it from the method? I am working with VueJs 2.

If you require any additional information, please do not hesitate to reach out. Thank you!

Answer №1

When working with the .then() callback, it's important to note that the this keyword refers to the callback function itself, not the data being proxied.

To resolve this issue, you can assign the correct this context to another variable and use that instead.

Here's how you can update your code:

export default {
    name: "Contact",
    components: {
        FooterComponent: FooterComponent,
        NavigationComponent: NavigationComponent
    },
    data() {
        return {
            locale: Cookie.get('locale'),
            nameAndLastName: '',
            email: '',
            subject: '',
            message: '',
            showPopUp: false
        }
    },
    methods: {
        sendEmail(e) {
            var self = this; // Assign context to 'self' variable
            e.preventDefault();
            this.$validator.validateAll();
            if (!this.$validator.errors.any()) {
                let params = new URLSearchParams();
                params.append('nameAndLastName', this.nameAndLastName);
                params.append('email', this.email);
                params.append('subject', this.subject);
                params.append('message', this.message);

                axios.post(this.$apiUrl + `rest/api/public/Contact/contact`, params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(function (response) {
                        if (response.statusText === 'OK') {
                            console.log(this.showPopUp);
                            self.showPopUp = true; // Update like this
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        // Throws error TypeError: Cannot read property 'showPopUp' of undefined

                    });
            }
        }
    },
    mounted: function () {
        console.log('test');
        console.log(this.showPopUp);
    },
}

Alternatively, you can make use of ES6 arrow functions where the this is lexically scoped:

.then((response) => {
  if (response.statusText === 'OK') {
    console.log(this.showPopUp);
    this.showPopUp = true;
  }
})

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

JavaScript: What is the concept of overriding function named params?

function retrieveData({item1 = "blue", item2 = 7}) { console.log('theItems'); console.log(item1); console.log(item2); } retrieveData( { item1: 'pink', item2: 9 } ); I've come across conflicting i ...

Incorporating graphics into a React component

Currently exploring React JS and looking to dive into the practical side of things. Following a documentation tutorial that constructs a basic comment system. I've replicated the component structure outlined in the tutorial: PostBox PostList Pos ...

What is the procedure for altering the location of a mesh within the animate() function in three.js?

In my implementation of a three.js mesh (found in three.js-master\examples\webgl_loader_collada_keyframe.html), I have a basic setup: function init() { ... ... var sphereGeometry = new THREE.SphereGeometry( 50, 32, 16 ); var sphereMater ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

Divide the pair of arrays that are transmitted via JSON

I combined two arrays and passed them through JSON, as shown below: $result = array_merge($json, $json1); echo json_encode($result); Now, to retrieve the data, I am using the following code: $.getJSON('./tarefasaad52', function (data) { } How ...

Tips for creating a loading page that displays while your website loads in the background

Is there a way to display a loading animation or image while my website is loading in the background? I've noticed that it takes about a minute for my website to fully load. I attempted to use <meta http-equiv="refresh" content="1000 ...

Vue-formulate - Collapsible group item toggle functionality

Can we implement collapsible group items? <FormulateInput type="group" name="employments" :repeatable="true" label="Employments" add-label="+ Add Employment" #default="groupProps"> & ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Verify if the username is already in use

Is it possible to validate the existence of a username while the user is entering it in a textbox or immediately after they finish typing? Should I use Jquery or Ajax for this task? Does anyone have any examples demonstrating how this can be done? ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...

Developing several sliders and ensuring they operate independently of each other

I am currently in the process of developing multiple sliders for a website that I am building. As I reach the halfway point, I have encountered a problem that has stumped me. With several sliders involved, I have successfully obtained the length or count ...

Fundamental JavaScript feature experiencing functionality issues

Greetings, this is my debut in this space and I am encountering some challenges as a beginner in the world of coding. It seems that passing arguments to parameters is where I'm hitting a roadblock, or perhaps there's a simple detail that I'm ...

Struggling to update a Knockout observable array

I'm attempting to send some data to a Knockout observable array. Despite receiving data from my AJAX call without any errors during script execution, I find that the userNames array remains empty when accessed. What could be causing this issue? UserH ...

"Upon inspection, the TrackerReact Container shows that the user's profile.avatar is set, yet the console is indicating that

Within my app, I designed a TrackerReact container named ProfileSettingsContainer. This container retrieves the user data with Meteor.user() and passes it to a function called user(), then sends this information to the ProfileSettings component. The main o ...

Error in Jquery validation caused by incorrect file extension type

Within my HTML form, I have multiple inputs set up for validation purposes: <form role="form" id="addForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="userName">U ...

Using Strapi and Next.js to retrieve user information

After searching for similar questions with no luck, I'm reaching out for help. Building an authentication system using Strapi and Next.js, I'm faced with a task that seems simple but eludes me. The main question is: How can the client retrieve u ...

There appears to be no data available from the Apollo Query

I'm facing an issue with the returned data from Apollo Query, which is showing as undefined. In my code snippet in Next.js, I have a component called Image with the src value set to launch.ships[0].image. However, when running the code, I encounter a ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...

Guide on accessing a nested child component's div element upon mounting in Vue.js

One issue I am facing is with scrolling to an element when the page opens. It's similar to scrolling to an anchor. I pass the div id as props to a nested child component. Upon mounting, I invoke a method called scrollToSection where the scrolling logi ...

ajaxStart event does not trigger when making an Ajax POST request

My ajaxStart event functions properly for ajax loads, but it does not work at all when I do a POST request. The following code is consistently rendered on all pages: $(document).ajaxComplete(function () { hideIcon(); if (stepState !== &a ...