Nuxt 3. Conditionally fetching data

Viewed 119

I wonder if it's possible to fetch data conditionally in global await?

<script setup>
...
const test = ref([]);
if (myCondition) {
    const {
        data
    } = await useAsyncData('test', () => $fetch('/my/api/call'));
    test.value = data.value;
}
</script>

If I write it this way, test value is not reactive and is not updated in the template

1 Answers

It should work like this:

<script setup>
const myCondition = ref(false)
const test = ref()

watch(myCondition, async () => {
  if (myCondition.value) {
    const { data } = await useFetch('https://jsonplaceholder.typicode.com/posts/1')
    test.value = data.value
  } else {
    test.value = undefined
  }
})
</script>

<template>
  <div>
    <a @click="myCondition = !myCondition">Toggle!</a> <br />
    {{ test }}
  </div>
</template>

You could also use test.value = $fetch(...) instead of useFetch but you'll lose the caching then.

Related