Tips for leveraging data across different hooks within Vue.js

Within my Vue.js project, I am making a request using the Axios package in the created() hook. The response data is being added to an array named coordinates. However, I am encountering an issue when trying to access this array outside of the created() hook, such as in the mounted() hook or within methods defined in the methods property.

Currently, when attempting to reference self.coordinates outside of the created() hook, it returns undefined. Using this.coordinates results in [__ob__: Observer] being displayed. What am I doing wrong?

export default {
    name: "Map",
    data() {
        return {
            coordinates: [],
        }
    },
    created() {
        let self = this;
        axios.get('URL').then(function (response) {
            let coordinates = [];
            for (let i = 0; i < response.data.length; i++) {
                coordinates.push([response.data[i]["LATITUDE"], response.data[i]["LONGITUDE"]]);
            }
            self.coordinates = coordinates;
        });
    },
    mounted() {
        console.log(self.coordinates); // undefined
        consol.log(this.coordinates);  // [__ob__: Observer]
    },
}

Answer №1

If we were to optimize this code for better reusability, I would recommend refactoring the logic into separate methods that can be called from anywhere in the program. By doing so, it not only improves maintainability but also enhances flexibility. In the code snippet provided below, I have demonstrated how this approach can be implemented by calling the method directly upon mounting. Another alternative could be utilizing watchers.

You can view the working example on jsFiddle here: https://jsfiddle.net/63mfoxhw/1/

new Vue({
    el: '#app',
    data() {
        return {
            coordinates: []
        }
    },
    mounted() {
        let self = this;
        axios.get('https://api.weather.gov/').then(function (response) {
            self.coordinates = response.data;
            self.handleResponse();
        });
    },
  methods: {
    handleResponse: function () {
        console.warn(this.coordinates.status);
    }
  }
})

Answer №2

Instead of using mounted, I suggest using watch. By having a watch method in place, you can call a link which may take time to load the data, and the watch method will trigger once your data is updated...

watch: {
    coordinates: {
      handler: function (updateVal, oldVal) {
        console.log(updateVal)
      },
      deep: 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

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Is there a way to differentiate the color of an active link from an inactive one, so users can easily identify which link they are currently viewing?

How can I customize the color of text for the active page on my website's sidebar? For example, I have two hyperlinks, one for HOME and one for ABOUT. When a user clicks on the HOME link, I want the text color to change to green while the ABOUT link r ...

[Vue Alert]: Render Error - "TypeError: Unable to retrieve the 'getters' property of an undefined object"

Here is the code snippet from my app.js file. Can someone please review it and confirm if I have defined the items correctly according to the Vuex documentation? import store from "./store"; require('./bootstrap'); window.Vue = require( ...

The drop-down component is being filled with data but unfortunately, only dummy data is functional at the

Having trouble populating data in the drop-down component. Everything works fine when using dummy JSON data as shown in the comments. The GET request service retrieves the necessary data, and then I assign the response to the appropriate variable. The GET ...

Using JavaScript to assess the outcome of a form utilizing an if statement

Trying out a method to assess a result by utilizing an if statement on the form provided below. Upon dividing the 2nd result by the 1st result, an average percentage is calculated. If this percentage is equal to or higher than 55, then the outcome is label ...

Tips on integrating the createjs library into a ReactJS project

Hey there! I'm currently working on developing a canvas-based app using ReactJS, and I need to integrate the CreateJS library. As a newcomer to ReactJS, I've been struggling to figure out the best approach. I've tried two different methods - ...

Strategies for efficiently updating specific objects within a state array by utilizing keys retrieved from the DOM

I am trying to figure out how to use the spread operator to update state arrays with objects that have specific ids. Currently, I have an array called "todos" containing objects like this: todos: [ { id: "1", description: "Run", co ...

How to Display Custom Messages for Password Validation in Vuetify?

I currently have a password rule set up as follows: passwordRule(value){ const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/; return ( pattern.test(value) || "Min. 8 charact ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

problem encountered when inserting data (GET method) in a loop using window.location

I'm currently utilizing sailsjs to extract data from the GET parameter within the URL (mydomain.com/prod_master/addsupp). The specific page is /prod_master/addsupp, designed to receive GET parameters for database insertion. In my Javascript code, I ...

How can I preserve data in editable PDFs with Angular and JavaScript?

Need help with savedoc() functionality <iframe [src] ="fileurl" #iframe> </iframe> <button (click)="saveDoc()"> </button> Having trouble accessing edited PDF content in Typescript: /*api cal ...

Is it possible to stop slick slider from automatically scrolling when I click on the navigation slider?

I am in need of utilizing the slider syncing feature (example can be found here by scrolling down), However, I have noticed that clicking on the navigation slide causes the entire navigation to auto-slide further. My goal is to disable this function so th ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

displaying data once "other" is chosen from a dynamic chart

I am having an issue with a dynamic table where I have a dropdown list with the option "other", and I want to display additional input when "other" is selected. Currently, the function I have only hides the input that is always visible and does not show ...

Retrieving AJAX Response and Assigning it to a JavaScript Variable

I've dedicated countless hours searching for assistance on how to implement an AJAX call in Javascript to communicate with a PHP script. My goal is to add a value to a table, retrieve the ID of the newly inserted row, and use that ID in a form submis ...

Troubleshooting Node.js MySQL Connection Problems in Railway

I'm currently in the process of uploading my very first web application to Railway. The backend is Node.JS and the database is MySQL. Initially, everything was functioning correctly before I made some modifications to the backend to connect it with th ...

Iterating through a two-dimensional array in Javascript

Hosting a gathering means serving pizza, but each guest has specific topping preferences. As more people RSVP, you'll need to anticipate the amount of pizza to order and which toppings to include. To simplify this task, you can develop a JavaScript pr ...