javascript - Nuxt 3 and Vue 3 onMounted call function useFetch function not getting data form APIs - Stack Overflow

Hi i am new in Nuxt and Vue. I am using Nuxt framework to get data form APIs. I want to get data from A

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(`/${id}`);
      
      console.log("after this" + id);
      console.log(data.value);
      
   }; 

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

Otuput in console
after this 2
null

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./products/${id}`);
      
      console.log("after this" + id);
      console.log(data.value);
      
   }; 

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

Otuput in console
after this 2
null
Share Improve this question asked Jun 21, 2023 at 20:59 GaganGagan 751 gold badge1 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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

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./nuxt/nuxt/issues/13471#issuement-1889647593

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743777050a4505423.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信