vuejs3 updated life cycle hook not being called when state is changed

1.8k Views Asked by At

I'm learning Vue.js coming from React. I'm confused about the updated life cycle hook. no matter what state I change I can't get it to run. I have a console.log inside the updated hook and I've set a setTimeout in the mounted hook. the setTimeout callback runs and changes the state which changes what is displayed on the DOM although I don't ever see the console.log from the updated hook. I'm not sure why the update is not firing

NOTE: I'm using Vue.js 3.

<template>
    ...other components
</template>

<script>
export default {
  name: 'App',
  data: () => ({
    state: 'initial'
  }),
  updated () {
    console.log('UPDATED!!!')
  },
  mounted () {
    setInterval(() => {
      this.state = 'changed'
      console.log('changing')
    }, 1000)
  }
}
</script>
1

There are 1 best solutions below

1
tony19 On

The updated lifecycle hook only runs when the template has been updated (was re-rendered), which would only occur when a property used in the template has changed values.

Since state was modified, and the updated hook did not run, that would imply that the template is not using state. Also note repeatedly setting state to the same value would only trigger the hook once for the new value (assuming the template needed state).

For example, the following snippet would trigger the updated hook periodically, as the timer callback toggles state, which is rendered in the template:

<template>
  <div>{{ state }}</div>
</template>

<script>
export default {
  name: 'App',
  data: () => ({
    state: 'initial'
  }),
  updated () {
    console.log('UPDATED!!!')
  },
  unmounted () {
    clearInterval(this._timerId)
  },
  mounted () {
    this._timerId = setInterval(() => {
      this.state = this.state === 'changed' ? 'initial' : 'changed'
      console.log('changing')
    }, 1000)
  }
}
</script>

demo

That said, there's usually a better way to do things in Vue instead of the updated hook (e.g., using a watch on a specific prop), but that depends on your actual use case, which isn't clear in the question.