Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs

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
like image 784
Gagan Avatar asked Oct 15 '25 09:10

Gagan


2 Answers

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

like image 102
learntheropes Avatar answered Oct 18 '25 00:10

learntheropes


Went actually through the same error, and always using nextTick seemed wrong.

The real reasons behind this is the misuse of the useFetch which is reactive and shoud be used only in the root part of the setup script. If you use $fetch the problem won't appear.

https://github.com/nuxt/nuxt/issues/13471#issuecomment-1889647593

like image 34
Alex Pereira Avatar answered Oct 18 '25 00:10

Alex Pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!