Trying to assign a property to an undefined variable inside a function

At the moment, I am configuring error messages on a login page for an extension using vue, and encountering issues within the importCreds() function.

data(){
    return {
    url:'',
    apikey:'',
    error:'',
    }
},
methods:{
    accountSummaryButton(){
        if (localStorage.getItem("accounts") == null)
            this.error = 'There are no available accounts.';
        }
        else
            // STUFF
    },
    saveLogin(event){
        let app = this;
        if (!app.getAccountData(app.url,app.apikey,this.method))
            this.error = 'An error has occurred, please check Url and API Key.';
        else {
            //STUFF
        }
    },
    importCreds(){
        let app = this;
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(
                tabs[0].id,
                {action: "import_creds"},
                function(response) {
                    if (response){
                        app.url = response.affiliateurl
                        app.apikey = response.apikey
                    } else
                        this.error = 'Go to your affiliate site.';
                }
            );
        });
    },
},

Is there a straightforward way that I might be overlooking to access error in this function?

Answer №1

The importCreds function still refers to the original this object, but the

chrome.tabs.query({}, function(tabs) {})
does not. To maintain that reference, you can assign this to a variable like (let app = this), and then use app.error.

data () {
    return {
      url: '',
      apikey: '',
      error: '',
    }
},
methods: {
    accountSummaryButton () {
        if (localStorage.getItem("accounts") == null) {
            this.error = 'There are no available accounts.';
        } else {
            // STUFF
        }
    },
    saveLogin (event) {
        let app = this;

        if (!app.getAccountData(app.url,app.apikey,this.method)) {
            this.error = 'An error has occured, please check Url and API Key.';
        } else {
            // STUFF
        }
    },
    importCreds () {
        let app = this;

        chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            chrome.tabs.sendMessage(
                tabs[0].id,
                { action: "import_creds" },
                function(response) {
                    if (response) {
                        app.url = response.affiliateurl
                        app.apikey = response.apikey
                    } else {
                        app.error = 'Go to your affiliate site.';
                    }
                }
            );
        });
    },
},

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 inserting HTML into elements using Angular

Recently, I delved into Angular and decided to experiment with Ajax by fetching a document to display on my webpage. The process worked flawlessly, but now I face a new challenge: injecting HTML content into a DOM element dynamically. Typically, this task ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

"How to prevent users from using the back button on Google Chrome and Edge browsers

window.history.pushState(null, null, location.href); window.addEventListener('popstate', () => { history.go(1); alert('The use of back button is restricted.'); }); An issue has been identified where the code snippet above d ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

Trigger a unique event using Vanilla JS and then detect it on Vue instances

I am currently in the process of incorporating multiple Vue instances into my website. I have encountered issues preventing me from making the entire website a Vue instance and using components due to potential conflicts and other complications. For examp ...

AngularJS wildcards can be used in filters for a versatile approach

Is there a more efficient way to filter a list of values using wildcards? searchString = "ab*cd" The goal is to retrieve all values that begin with "ab" and end with "cd". One approach I've tried involves splitting the string into multiple substrin ...

Can we expect React's useState to wait before executing subsequent logic, or will it immediately update the state and trigger a re-render

I have a specific scenario in my code where I am using the useState setter function in React to update a value on line 5. Everything seems to be functioning well without any errors, but I'm curious about something. Since setState updates the state and ...

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two probl ...

What are some strategies to enhance the efficiency of this code and reduce repetition?

Here's an overview of the component in question export default () => { const { currentUser, logout } = useAuth(); const [sideBarOpen, setSideBarOpen] = useState(false); const theme = useTheme(); const classes = useStyles(); const isSmall ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...

Working with Vue.js: accessing nested data from child components within a v-for loop

When working with a v-for loop, my goal is to group every 4 results retrieved from the API into a single row. <div v-for="(item, index) in this.info.length/4" :key="item"> <el-col v-for="thing in this.info" :key="thing"> {{ thing }} ...

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Utilize Javascript to extract and showcase JSON data fetched from a RESTful API

I'm attempting to use JavaScript to pull JSON data from a REST API and display it on a webpage. The REST call is functioning correctly in the Firefox console. function gethosts() { var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://10 ...

Numerous instances of Codemirror

I have the ability to generate and exhibit multiple dynamic codemirror instances, however, I am having trouble referencing them using the code snippet below. I suspect that the problem lies in creating a dynamic function name (not entirely sure how to ac ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Ensure that any modifications made to an Angular service are reflected across all components that rely on that service

I am currently in the process of replicating a platform known as Kualitee.com, which serves as a test-management tool utilized by QA Engineers. Within Kualitee, users can access multiple projects, each containing various test cases and team members. The ab ...

Disallow/bound the position of the marker on Google Maps

Is there a way to restrict the placement of markers on a map? I am looking for a solution that allows me to limit the marker position within a specific area, such as a town, with a radius of 10km. It should prevent users from dragging or creating new mark ...