Ujwal Pradhan
Ujwal Pradhan

Reputation: 45

Vue promise error, I am having error with promise

While the same method works just fine with another api call, fetch from this api is getting me error on promise. the error reads Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'json')

My fetch code reads as below:

import { ref } from "vue";
export default {
async setup() {
    const prompProducts = ref(null);
    const bc_prompProducts = await fetch(
      "https://booking.hemantbhutanrealestate.com/api/v1/get_frontend_products"
    );
    prompProducts.value = await bc_prompProducts.json();
return {
      prompProducts,
   };
  },
};

While this same method works without error on my other api calls, am getting error on this one. Please help, the site is on production already!

Upvotes: 1

Views: 558

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

You can put your async call in function and call it, or you can use onMounted hook:

const { ref, onMounted } = Vue
const app = Vue.createApp({
  setup() {
    const prompProducts = ref([]);
    onMounted(async() => {
      const bc_prompProducts = await fetch(
      "https://booking.hemantbhutanrealestate.com/api/v1/get_frontend_products"
      )
      prompProducts.value = await bc_prompProducts.json()
    })
    return { prompProducts }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="pro in prompProducts" :key="pro.id">
    <p>{{ pro }}</p>
  </div>
</div>

Upvotes: 1

Related Questions