Watching has not been initiated

My hierarchy is structured like this:

Root

  • App

    • TimelineItem
      • TimelineMetadata

In app.vue, I make HTTP requests on mounted and populate a timeline variable with the fetched data.

<template>
  <div id="app">
    <div class="loading" v-show="loading">Loading ...</div>
    <table class="timeline">
        <TimelineItem v-for="event in timeline" :key="event.id" :item="event" :players="players" :match="match"></TimelineItem>
    </table>
  </div>
</template>


export default class App extends Vue {
  ... 

  public timeline: any[] = [];

  public mounted() {
    ...
    if (!!this.matchId) {
      this._getMatchData();
    } else {
      console.error('MatchId is not defined.  ?matchId=....');
    }
  }

  private _getMatchData() {
    axios.get(process.env.VUE_APP_API + 'match-timeline-events?filter=' + JSON.stringify(params))
      .then((response) => {
        this.loading = false;
        this.timeline = [];
        this.timeline = response.data;
  }

...
}

The TimelineItem component looks like this:

<template>
  <tr>
    <td class="time">
      ...
      <TimelineItemMetadata :item="item" :match="match"></TimelineItemMetadata>

    </td>
  </tr>
</template>

....

@Component({
  components: {
    ...
  },
})
export default class TimelineItem extends Vue {
  @Prop() item: any;
  @Prop() match: any;
  @Prop() players: any;
}
</script>

Lastly, the TimelineItemMetadata component displays the item passed to it:

<template>
  <div>
    TEST1
    {{item}}
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';

@Component({})
export default class TimelineItemMetadata extends Vue {

  @Prop() item: any;
  @Prop() match: any;


  @Watch('match') onMatchChanged() {
    console.log('TEST');
  }
  @Watch('item') onItemChanged() {
    console.log('ITEM', this.item);
  }

  public mounted() {
    console.log('Timeline metadata item component loaded');
  }

}
</script>

The @Watch for item and match is not triggering even though there is data present according to Vue-devtools. Why is my @Watch not being triggered?

Answer №1

Upon examining your scenario, it appears that the match and item props within the TimelineItemMetadata property remain static over time; they are initially defined by the App component upon mounting.

After reviewing this article, it seems necessary to include an explicit immediate parameter in a watcher in order for it to activate the first time a prop is modified..

Therefore, I believe the corrected approach should be as follows:

// typo has been corrected
@Watch('match', {immediate: true}) onMatchChanged() {
  console.log('TEST');
}
@Watch('item', {immediate: true})) onItemChanged() {
  console.log('ITEM', this.item);
}

Answer №2

If anyone else is encountering the same issue as me...

I ended up wasting a significant amount of time because I mistakenly reset the state using a new instance of the state object (Incorrect), instead of modifying its properties directly (Correct).

Remember, avoid replacing your state object entirely with a new one. Instead, just modify its individual properties.

export interface ISample {
    property1?: string;
    property2?: string;
}

export interface SampleState {
    current: ISample;
}

function getDefaultState (): SampleState {
    return {
        current: {
            property1: undefined,
            property2: undefined
        }
    }
}

export const state = getDefaultState

export const mutations: MutationTree<SampleState> = {
    setValue (state, value: ISample) {
        state.current.property1 = value?.property1
        state.current.property2 = value?.property1 // Issue here, should be value?.property2
    },

    reset (state) { // Correct way to reset
        state.current.property1 = undefined
        state.current.property2 = undefined
    },

    reset2 (state) { // Incorrect method! Caused @Watch functionality to break,
        state.current = getDefaultState().current
    }
}

export const actions: ActionTree<SampleState, {}> = {
    setValue ({ commit }, value: ISample) {
        commit('setValue', value)
    },

    reset ({ commit }) {
        commit('reset')
    }
}

export const getters: GetterTree<SampleState, {}> = {
    property1: (store) => {
        return store.current.property1
    },

    property2: (store) => {
        return store.current.property2
    }
}

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

The parameter type 'string | null' cannot be assigned to the argument type 'string'. The type 'null' is not compatible with the type 'string'.ts(2345)

Issue: The parameter type 'string | null' is not compatible with the expected type 'string'. The value 'null' is not a valid string.ts(2345) Error on Line: this.setSession(res.body._id, res.headers.get('x-access-token&ap ...

What steps can be taken to resolve an ESLing error in this situation?

Check out this code snippet: <template v-if="isTag(field, '')"> {{ getItemValue(item, field) ? getItemValue(item, field) : '&#8211'; }} </template> An issue has been identified with the above code: Er ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Resolving Unrecognized Vue Variable in PhpStorm

I'm encountering an issue with my Vue script in PhpStorm. Despite setting the variable redirect_to, I am getting an Unresolved variable syntax error during debugging. Please refer to the image below for further information. How can I resolve this prob ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

Utilizing the Controller with react-hook-form and material-ui to enhance the functionality of the FormControlLabel and

When using Material-ui with react-hook-form, it is recommended to use <Controller along with the render method instead of using "as = {xy-control}". Additionally, avoid mixing controller with inputRef = {register}. Using a single control is not an issue ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

Arrange a JSON response in descending order and filter out specific values

Currently, I'm encountering a challenge when trying to extract a specific attribute from my JSON response. The issue arises when I attempt to sort the results based on the `percentage_match` in descending order. Once sorted, my goal is to create an ar ...

Navigating the loop in Vue using JavaScript

I'm facing an issue where I need to send data at once, but whenever I try sending it in a loop, I end up getting 500 duplicate id status errors. I have a hunch that if I click on something in JavaScript, the data might be sent all at once. assignment ...

Creating a parent component within a child component in Vue.js

My application features a key component: export default { name: 'category', props: { ref: Object, asLabel: Boolean }, components: { Products } } The template in the Products component includes: <category :asLabel="tr ...

Working with JSON data from a .NET backend in combination with Vue 3 frontend components

Currently immersed in developing a Single Page Application using Vue 3 and .NET Web API (EF Core 5). The main goal is to showcase a roster of artists, each with multiple genres attached to them. Successfully established a many-to-many relationship between ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

The Vuetify v-img component fails to display images when using absolute paths

Having a bit of trouble here: I want to showcase an image using an absolute path in Vuetify with the v-img tag, but for some reason, it's not displaying. I attempted to use :src="require('path/to/img')", but it throws an error saying "This ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Configuring OIDC for a backend API and frontend single-page application

Currently, I am working on a project that involves a Django backend with Django Rest Framework serving an API, and a Vue.js frontend SPA consuming the API. However, I seem to be encountering some CORS issues related to authentication. To implement the Aut ...

Enhance a subject's behavior by overriding the .next method using a decorator

Currently, I am working on an Angular application where I have numerous Subjects, BehaviorSubjects, and ReplaySubjects as properties in various services. I am attempting to create a TypeScript decorator that can be added to some of these Subjects to enhanc ...

Attempting to use a string as an index for the type `{ firstName: { inputWarning: string; inputRegex: RegExp; }` is not allowed

const checkRegexSignUp = { firstName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, lastName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, } const change = (e: ChangeEvent<HT ...

RxJS: the art of triggering and handling errors

This is more of a syntax question rather than a bug I'm facing. The process is straightforward: Send an HTTP request that returns a boolean value If the boolean is true, proceed If the boolean is false, log a warning and stop the flow. To handle ...

Learn the process of dynamically setting the image src from a local json file in Vue.js3

I am facing a challenge with my App.vue file that has a V-for loop to create a Card Component. The Card Component receives data through a Prop and everything works perfectly, except for the images. Here is the code in my App.vue file: <DevJobCard :Job= ...