Search code examples
vue.jsvuejs3vue-composition-api

Vue.js 3 - replace/update reactive object without losing reactivity


I need to update a reactive object with some data after fetching:

  setup(){
    const formData = reactive({})

    onMounted(() => {
      fetchData().then((data) => {
        if (data) {
          formData = data //how can i replace the whole reactive object?
        }
      })
    })
  }

formData = data will not work and also formData = { ...formdata, data }

Is there a better way to do this?


Solution

  • According to the official docs :

    Since Vue's reactivity tracking works over property access, we must always keep the same reference to the reactive object. This means we can't easily "replace" a reactive object because the reactivity connection to the first reference is lost

    reactive should define a state with nested fields that could be mutated like :

     setup(){
        const data= reactive({formData :null })
    
        onMounted(() => {
          fetchData().then((data) => {
            if (data) {
              data.formData = data 
            }
          })
        })
    
      }
    

    or use ref if you just have one nested field:

      setup(){
        const formData = ref({})
    
        onMounted(() => {
          fetchData().then((data) => {
            if (data) {
              formData.value = data 
            }
          })
        })
    
      }