1

Hi i am new in Nuxt and Vue. I am using Nuxt framework to get data form APIs. I want to get data from APIs when onMounted method call.

I created saprate function to call api. That api get data with product id. If i call API without onMounted method it is working fine but when i call function in OnMounted method it is not working. always get "null" value.

Code given blew

<script setup>

    const product = async (id) => {
      
       const { data, pending, error } = await useFetch(`https://fakestoreapi.com/products/${id}`);
      
      console.log("after this" + id);
      console.log(data.value);
      
   }; 

    onMounted(async () => { 
      product(2); 
      
    });
</script>

Otuput in console
after this 2
null
Gagan
  • 35
  • 5

1 Answers1

1

I don't think this is due to onMounted but it seems to be a timing issue

Using nextTick as follows solve the issue:

import { nextTick } from 'vue';

onMounted(async () => {

  await nextTick();

  await getProduct(2);
});

I created a working reproduction for you to test here

learntheropes
  • 444
  • 3
  • 11