Using Vue: What is the best way to invoke a different method within a callback function?

After the save_key() function is executed, I need to invoke the get_data() function. However, I keep encountering a

Cannot read property 'get_data' of undefined
error. My assumption is that this error occurs because the function is called from a callback. How can I resolve this issue?

methods: {
    async get_data(){
        var response = await axios.get("http://127.0.0.1:8000/retrieve_user_data");
            this.keys = response['data']
    },

    save_key(){
        var key_data = {'action': 'save', 'key': this.form.key}

        return axios({
          method: 'post',
          url: 'http://127.0.0.1:8000/save_data/',
          data: key_data,
          withCredentials: true,
          headers: {}
        }).then(function (response) {
            this.get_data()
        })

    }
}

Answer №1

The issue arises from the scope of 'this' being set to the global(window) object in your callback function. To resolve this, you can either utilize an arrow function or introduce a placeholder variable for 'this'. One potential solution is to update your save_key function as shown below:

save_key(){
    const self = this;
    var key_data = {'action': 'save', 'key': this.form.key}

    return axios({
        method: 'post',
        url: 'http://127.0.0.1:8000/save_data/',
        data: key_data,
        withCredentials: true,
        headers: {}
        })
        .then(function (response) {
            self.get_data();
        })

    }

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

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

When attempting to retrieve the innerHTML of a <div> element within a <Script> tag, the value returned is undefined

Utilizing a masterpage to create a consistent header across all content pages, I encountered an issue on one page. I needed to retrieve the innerHTML of a div element and pass it to an input control on the same page in order to access the updated innerHTML ...

Utilize a service within a different service in the same module with code reference #1250

Within module A, I have two services/providers. The first is called ServiceA1 and is marked as @Injectable(). The second service/provider is named ServiceA2, also marked as @Injectable(). I am attempting to inject ServiceA1 into ServiceA2 using the follow ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...

Utilize angularjs daterangepicker to refine and sift through data

I am currently utilizing the ng-bs-daterangepicker plugin by ng-bs-daterangepicker and encountering difficulty in filtering when selecting a start date and end date. Below is a snippet of my code: <input type="daterange" ng-model="dates" ranges="range ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

Eliminate redundant data by utilizing oData to streamline information

I'm trying to clean up my data and eliminate duplicates using oDATA. Currently, I am using !summary=Name in my query, however it's not creating groups and providing the results as expected. Below is my query: http://localhost:12585/OData.svc/Med ...

Clicking outside the navigation container will not cause it to disappear completely

When the width of my navigation bar reaches a maximum of 560px, a hamburger menu appears for mobile devices. I want to implement a functionality where clicking on a navigation item (e.g., About) will close the nav-container instead of making it disappear c ...

Module 'path-to-regexp' not found

Currently, I am facing an issue while attempting to incorporate the library path-to-regexp into my TypeScript project. Despite using npm install path-to-regexp --save, with and without the --save flag, the import is still not functioning as expected. Upon ...

Using JSON files in conjunction with createI18n in Vue

Suppose I have a Vue project with a main.js file structured as follows: import { createI18n } from "vue-i18n"; import { createApp } from 'vue' import './styles/main.scss' import App from './App.vue' const i18n = cre ...

What could be causing the canvas circle to appear distorted and not truly circular?

My simple code is intended to draw a circle, but it's not appearing as expected. The coordinates seem to be shifted oddly. The canvas size is specified with style="width: 600px; height: 600px;". I've tested it on both Chrome and Safari, yet the r ...

Prevent duplicate form submissions/ throttle API calls when submitting a form in a Next.js application

In my Next.js application, I am facing an issue with the sign-up form. The problem occurs when the user clicks the "sign up" submit button multiple times quickly, resulting in the application sending out multiple fetch requests and displaying multiple toa ...

In JavaScript, split each element in an array into individual elements

Is there a way to split elements separated by commas into an array in JavaScript? ["el1,el2", "el3"] => ["el1", "el2", "el3"] I am looking for a solution to achieve this. Can you help me with that? ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

Guide to resetting an input form upon submission in ReactJS

I'm encountering some challenges in resetting my input form upon submission. My goal is to have the input field clear out its value after a successful form submission, but for now, I'd settle for it simply resetting on submit in general. Unfortun ...

Navigating through concealed components

I have encountered an issue while attempting to scrape a website. The challenge lies in the fact that I am unable to interact with hidden elements on the webpage. Here is the code snippet: Initial state li class="header-nav__item login header-item-is-hid ...

Leveraging an Array of Objects in JavaScript

Need help with my JavaScript code! I want to adjust the date in a Date object by adding specific days and then save it. Here is what I have so far: let orderIdDateCorrectionDict = [ { "orderId": "2020053100", "dayCorrection": -146 }, { "orderId" ...

Issue with command execution within execSync in node.js

I am facing an issue where a shell command works fine from the terminal, but when I try to run it from node.js, it gives me an error. Original Command awk -v RS='"[^"]*"' '{n+=gsub(/\n/, "&")} END{print n}& ...

Merge ReactCssTransitionGroup with React-route's Link to create smooth page transitions

React.js I'm facing an issue with the React.js code provided below. My goal is to set up the animation before transitioning to a new page using "React-router.Link" and ReactCSSTransitionGroup. Version: react: '15.2.1' react-addons-css-trans ...

Ways to conceal a div during the page loading process that is located in a separate PHP file

I am working with a PHP file that contains multiple PHP and JavaScript files being included. Within the AJAX .done(function(){ }) function, I am reloading my main page which includes all other files. The question is, how can I hide the div element inside a ...