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
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.com/nuxt/nuxt/issues/13471#issuecomment-1889647593
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With