When Vue.js is combined with axios, the data may not be properly updated

As I navigate through the world of Vue.js, I encounter a rather peculiar issue that has left me scratching my head ( at least in my humble opinion ).

Let's take a look at the code snippet:

import Vue from 'vue/dist/vue.js';
import axios from 'axios';

import './components/top-line';

new Vue(
  {
    el      : '#weatherWidget',
    data : {
      loading : false,
      error: '',
      current : null,
      daily   : null,
    },
    created : () => {
      let self = this;
      let form_data = new FormData();
      form_data.append( 'action', 'weather_request' );
      form_data.append( 's', window.vue_weather.s );

      self.loading = true;
      self.error = '';

      axios
        .post( window.vue_weather.ajax_url, form_data )
        .then(
          response => {
            let data = response.data;
            self.current = data.data.currently;
            self.daily   = data.data.daily.data;
            self.loading = false;

            console.log( self );
          }
        )
        .catch(
          error => {
            this.error = error;
          }
        );
    },
  }
);

Upon execution of the created method, I observe the following output in the console:

https://i.sstatic.net/uvPtT.png

Nevertheless, the Vue console paints a different picture:

https://i.sstatic.net/oA9j3.png

Despite the normal execution of the created function, the updating of Vue data remains elusive.

Could it be that I've overlooked something? Regrettably, my eyes fail to detect any missteps.

Any thoughts or insights on how to tackle this predicament?

REMARKS

  • The AJAX Request yields results
  • I did attempt using this instead of let self = this;

Answer №1

The issue lies in your usage of arrow functions within the created hook.

You can refer to the explanation provided at https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks,

Avoid using arrow functions for options property or callback, such as

created: () = console.log(this.a)
or
vm.$watch('a', newValue => this.myMethod())
. Since arrow functions are bound to the parent context, this will not refer to the Vue instance as expected, leading to errors like
Uncaught TypeError: Cannot read property of undefined
or
Uncaught TypeError: this.myMethod is not a function
.

You should use either

created() {

or

created : function() {

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

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

Strange response received from $http GET request on Android device running Crosswalk

I am attempting to retrieve data in JSON format from an API using AngularJS. The process is successful on iOS and desktop browsers, but I'm encountering a strange response when trying it on my Android device. The request code looks like this: $http({ ...

Can you explain the distinction between object allocation using the '=&' operator and the Object.create() method?

I have been delving deep into JavaScript object operations. My question revolves around the difference between const me = Object.create(person); and const me = person;. Both of these operations provide a similar output as they reference the object to a new ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

Navigating through React Native with TypeScript can be made easier by using the proper method to pass parameters to the NavigationDialog function

How can I effectively pass the parameters to the NavigationDialog function for flexible usage? I attempted to pass the parameters in my code, but it seems like there might be an issue with the isVisible parameter. import React, { useState } from 'rea ...

I have successfully resolved the CORS issue on my NodeJS application, but unfortunately, I am encountering errors when trying to fetch APIs on my React and JavaScript projects

Sample Code: const express = require('express'); const port = 3000; const router = express(); router.get('/', (req, res) => { res.send('Hi'); }) var request = require('request'); var options = { 'me ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

What is the best way to create a timer using JavaScript?

I'm looking for a reverse timer to track session timeout. I found a code on codepen that works as a clockwise timer, but my attempts to make it counterclockwise have failed. Can someone please suggest a solution? I want the timeout to be either 1 hour ...

steps to extract routing into its own component

Is it possible to extract this routing logic into a separate component? I attempted to use map but it didn't work I want to have only a single route, and change the 'path' when a specific link is clicked const Home = ({ code }) => { re ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Show the quantity of chosen selections utilizing ng-select

I have implemented the ng-select component for users to select multiple options from a list. My goal is to have the selected option displayed normally when only 1 option is chosen. However, if 2 or more options are selected, I want a custom template to sh ...

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

Is it possible to add a string into the v-model value using injection?

Can you please help me figure out how to update a value using v-model and pass along some additional string with the updated value? For example, can I do something like this: <input type="range" max="100" value="50" **v-model="mybtnstyle.width '%& ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

What is the process for activating source maps in Webpack?

I am trying to incorporate source maps in my webpack.config.js file. However, the existing webpack configuration in the open-source project I am working on seems unfamiliar to me. webpack.config.js // This entry point webpack config dynamically switches ...