How can I use the return values from useFetch, called in an event handler, in my template? #19447
Replies: 2 comments 9 replies
-
Hey, what about registering two reactive variables with At first products will be empty do you should be using ? operator for certain properties like title |
Beta Was this translation helpful? Give feedback.
-
It depends on your intention.If you want to execute the call e.g. on page loadWhat you did so far is start writing your own wrapper composable for I'd suggest returning the values and awaiting the function. See this StackBlitz for a working example. <script setup>
async function fetchProducts() {
const { pending, data } = await useFetch('https://api.nuxtjs.dev/mountains');
return { pending, data };
}
const { data: products, pending } = await fetchProducts();
</script>
<template>
<div class="p-10">
<div class="d-flex">
<h1>Products</h1>
<button class="btn btn-sm btn-primary ms-3" @click="fetchProducts">
Fetch Products
</button>
</div>
<div class="d-flex">
<p class="me-1" v-for="product in products">{{ product.title }}</p>
</div>
</div>
</template> PS: If you want to extract your composable at some point, please be aware of correctly keying it (see docs for more info on that). If you want to execute it after pushing a button (send a form/whatever)Best would be to use |
Beta Was this translation helpful? Give feedback.
-
This is what my code looks like:
How can I use the values returned from
useFetch
likepending
anddata
in my template? All the example I've seen seem to useuseFetch
at the top level and not inside a function.Beta Was this translation helpful? Give feedback.
All reactions