Nuxt 3 useFetch -- how to create reactive fields from returned data object?

868 views Asked by At

In my setup, I have the following:

const{ data, error } =  useFetch("http://localhost:8080/articles", { query: { page: dataPage }})

where datapage is a ref. This refetches whenever I change datapage, so that works well.

Now I want to get a field out of the data variable. Specifically, this works:

<div>{{ data.pageable }}</div> 

But I want to do this:

const pageable = toRef(data.pageable)

...

<div>{{ pageable }}</div>

This returns nothing (undefined). I also tried:

const { pageable } = toRefs(data)

with no luck.

How can I make a field of the data into a reactive value? Basically, I'm trying to avoid referencing "data" each time I want to access a field of the fetched data object.

1

There are 1 answers

4
Reagan On BEST ANSWER

Edit. I completely missunderstood OP's question.

If you are trying to avoid referencing the data, you can use the computed property.

~/pages/index.vue

<script setup>
const dataPage = ref( 0 )
const { data } = await useFetch( '/api/get-the-query', {
    query: { page: dataPage }
} )
const pageable = computed( () => data.value.pageable )

</script>
<template>
    <div>
        <div>
            Current pageable is: {{ pageable }}
        </div>
        <button
            v-for="num in 10"
            :key="num"
            @click.prevent="dataPage = num"
        >{{ num }}</button>
    </div>
</template>
<style scoped lang="css"></style>

API example ~/server/api/get-the-query

export default defineEventHandler((event) => {
    return {
        pageable: getQuery(event).page
    }
})