How to set the value of a reactive object (ref) with a value from another reactive object (ref)?

Viewed 4051

I am trying to set the value of a Form based on a data in another reactive variable called Product but it does not seem to work. The Form should set its values to the Product data if it is available, and if not then just use null.

This is a section of the vue component code:

props: {
    ProductID: {
      type: Number,
      default: null
    }
  },

setup (props) {
const Product = ref();

async function loadProduct(ProductID) { // Runs when `props.ProductID` changes using a watcher
      try {
        const Response = await $axios.get(`/api/product/${ProductID}`);
        Product.value = Response.data; // This is an array of data
      } catch (error) {
        console.log(error);
      }
    }
}


 const Form = ref({
      ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
 ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
    )}
}

In vue devtools I can see that Product is populated with data, but the values are never assigned to the Form keys - they are just null. If Product is reactive and so too is Form, why does this not work?

1 Answers

Your Form is only initialized when setup is first run, so it's only initialized but won't get updated. If you want Form to update when Product updates, you can make it computed property that relies on Product:

const Form = computed(() => ({
  ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
  ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
}))

Or you can manually update Form in loadProduct, this way whenever Product is reloaded, Form will also get updated:

const Form = ref({})
async function loadProduct(ProductID) { // Runs when `props.ProductID` changes using a watcher
      try {
        const Response = await $axios.get(`/api/product/${ProductID}`);
        Product.value = Response.data; // This is an array of data
        Form.value = {
          ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
          ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
        }
      } catch (error) {
        console.log(error);
      }
    }
}
Related