Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make every object property reactive?

Consider this simplified example:

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

I want to create a reactive reference for each property in the puppy object.

The easiest way is to do this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const puppyName = ref(puppy.name);
const puppyAge = ref(puppy.age);

However, this is quite repetitive, so I’m wondering: is there a more generic and type-safe approach to achieve the same?

>Solution :

How about doing it manually?

<script setup  lang="ts">
import { ref, Ref } from 'vue'

function createReactiveRefs<T>(obj: T): { [K in keyof T]: Ref<T[K]> } {
  const reactiveRefs: any = {};

  for (const key in obj) {
    reactiveRefs[key] = ref(obj[key]);
  }

  return reactiveRefs;
}

interface Dog {
  name: string;
  age: number;
}

const puppy: Dog = {
  name: 'Snoop',
  age: 2,
};

const reactivePuppy = createReactiveRefs(puppy);
</script>

<template>
  {{ reactivePuppy.name.value }}
</template>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading