Nuxt Noob here. I want to create a Site that uses Directus as backend.
I followed tutorials about fetching data in Nuxt and using the Directus SDK.
On initial page load, everything seems fine and data is fetched correctly. But when I change the route and go back to the index.vue
the data is lost, won't, fetch again and therefore the page is not rendered.
I'm getting this error H3Error: Failed to fetch
and the global.value
is null
So what am I doing wrong? I know what to do in plain Vue, but what am I doing wrong with Nuxt?
Does this have to do with Live Cycle hooks, I'm not aware of in Nuxt? I don't think the problem is on the Directus side. It has to be something with the fetching in Nuxt or caching or live cycles or ... .
my code:
plugins/directus.js:
import { createDirectus, rest, readItems} from '@directus/sdk';
const directus = createDirectus('https://foo.bar').with(rest())
export default defineNuxtPlugin(() => {
return {
provide: { directus, readItems},
};
});
pages/index.vue:
<script setup>
const { $directus, $readItems } = useNuxtApp();
const { data: global } = await useAsyncData('global', async () => {
const response = await $directus.request($readItems('global'));
return response;
});
console.log(global);
</script>
<template>
<div class="flex px-5 bg-base-100 mt-9 sm:mt-0">
<p class="text-2xl">
bla bla bla
<NuxtLink to="/about">
{{ global.name }}
</NuxtLink>
{{ global.about }}
</p>
</div>
</template>
I also asked this question on the Nuxt-Subreddit r/Nuxt and the answer was this:
It’s only going to fetch it once. Either SSR (server side) or client-side. You need to store the data in some form of state so that as your navigate client-side, the data remains accessible as it’s persisted across page views.
That is unless the SDK you’re using does re-fetching and updating or something like you have in libraries like TanStack Query. Though I’ve seen that more used in the React world.
For Nuxt using the built in fetching and combining it with useState or Pinia is the recommended approach.
So basically, I had the wrong understanding of how the built-in fetch in Nuxt is working.
I will use Pinia.