0
votes

I want to watch props passed to a composition function from setup:

async setup(props) {
  const { data } = await useOperation(query, props.isEdit);
}

and each time the value of isEdit changes, I want to do something in the watch:

export const useOperation = async (query, isEdit) => {
  const reload = ref(isEdit)
  watch(
    () => reload.value,
    (result) => {
      console.log(result)
    }
  )
  const { data } = await fetch(query)

  return {
    data
  }
}

When props.isEdit changes, the watch is not triggered. How do I make this work?

1

1 Answers

1
votes

You should watch the props change directly in setup:

async setup(props) {
  const { data } = await useOperation(query, props.isEdit);

  watch(
    () => props.isEdit,
    (result) => {
      console.log(result)
    }
  )
}

By running:

watch(
  () => reload.value,
  (result) => {
    console.log(result)
  }
)

You are watching the reload variable instead of props.isEdit, and since useOperation is only run once during setup, and reload is not exposed anywhere, its value will never be changed.


Or if you do want to watch in useOperation, make sure you pass in the props as parameter, and watch for props.isEdit:

export const useOperation = async (query, props) => {
  watch(
    () => props.isEdit,
    (result) => {
      console.log(result)
    }
  )
...