Search code examples
vue.jsvuejs3fetch-apivuetifyjs3

Any alternative to useLazyAsyncData and watch() to post process a string?


I'm receiving a string instead of json from an API. I'm trying to do the conversion through watch() but it's never called.

How can I fix it ? And is there a better alternative to do such post-process ?

<template>
  <h1>Report</h1>
  <v-data-table
    :items="reportJson"
    :headers="headers"
  ></v-data-table>
</template>

<script setup>

const headers = reactive([
  { title: "First Name", key: "first_name" },
  { title: "Last Name", key: "last_name" },
  { title: "Gender", key: "gender" },
]);

const { pending, data: report } = useLazyAsyncData("report", () =>
  $fetch(
    "https://random-api.com/report/hash123"
  )
);

const reportJson = reactive();

watch(report, (newReport) => {
  console.log("watch() called");
  reportJson = JSON.parse(newReport);
});

</script>

Solution

  • You could add immediate:true to call the watch at the first data change :

    const reportData = reactive({json:{}});
    
    watch(report, (newReport) => {
      console.log("watch() called");
      reportData.json = JSON.parse(newReport);
    },{immediate:true});