Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Load a watcher only after the component has loaded

Hello,

I have this watcher.

watchEffect(() => {
	if (student.value.path_id) {
	  apiProject.index(student.value.path_id).then(response => {
		  projects.value = response.data.projects
		  if (student.value.path_id == savedPathId.value) {
		  	student.value.project_id = savedProjectId.value
		  } else {
		  	student.value.project_id = projects.value[0].id
		  }
	  })
	}
})

I explain a bit : when the component loads, it initializes the student.value.path_id property and it triggers the watcher. But I want the watcher to trigger only when a user selects a new path in the form.

What can I do to avoid the watcher to trigger when the component loads ?

Thanks for your help.

V

0 likes
2 replies
s4muel's avatar

i am not proficient in Vue (sorry about that), but something like this doesn't work?

let componentLoaded = false;

watchEffect(() => {
  if (componentLoaded) {
	//...
  } else {
    componentLoaded = true;
  }
});

thats what came to my mind, but here is a suggestion from AI to use watch() instead, is it of any use?

import { watch } from 'vue'

watch(
  () => student.value.path_id,
  (newVal, oldVal) => {
    if (oldVal === undefined) {
      return;
    }
    apiProject.index(newVal).then(response => {
      projects.value = response.data.projects
      if (newVal == savedPathId.value) {
        student.value.project_id = savedProjectId.value
      } else {
        student.value.project_id = projects.value[0].id
      }
    })
  }
)
1 like

Please or to participate in this conversation.