N
Nuxt6mo ago
Tom

Preventing Refetching in Component

Hey everyone, I'm using useAsyncData with a key so useAsyncData('config'), what I thought the key did is if config already exists in the payload it will load from there rather than refetching. That way you can safely use useAsyncData inside components. This is super useful as you can just drop in components and the data will come with it. If you can have multiple components pulling from the data source, rather than making multiple requests it will load from the payload. I'm finding that I have a component that loads config data for the menu, each time the menu is unmounted and mounted it refetches data from the database endpoint. Have I misunderstood what they key does in useAsyncData and is there a way to make it behave like I described?
5 Replies
Tom
TomOP6mo ago
https://nuxt.com/docs/getting-started/data-fetching#caching-and-refetching useFetch and useAsyncData use keys to prevent refetching the same data. This was the part that lead be to believe it worked that way.
Tom
TomOP6mo ago
Requests keep happening on mount.
No description
localhostess
localhostess6mo ago
I had to use getCachedData like this in order to have it stop requesting from the api endpoint
const nuxtApp = useNuxtApp();
const {client} = usePrismic();

const {data: team} = await useAsyncData(
'team',
() => client.getSingle('team'),
{
transform: (team) => {
const teamMembers = team.data.team_members || [];
return teamMembers.slice(0, 2);
},
getCachedData: (key) =>
nuxtApp.payload.data[key] || nuxtApp.static.data[key]
}
);
const nuxtApp = useNuxtApp();
const {client} = usePrismic();

const {data: team} = await useAsyncData(
'team',
() => client.getSingle('team'),
{
transform: (team) => {
const teamMembers = team.data.team_members || [];
return teamMembers.slice(0, 2);
},
getCachedData: (key) =>
nuxtApp.payload.data[key] || nuxtApp.static.data[key]
}
);
localhostess
localhostess6mo ago
Alex explains it here, pretty cool! https://www.youtube.com/watch?v=aQPR0xn-MMk
Alexander Lichter
YouTube
Nuxt 3.8 - Client-side caching with getCachedData ✨
⚡️ Nuxt 3.8 was released just a day ago, packed with lots of amazing features. Among the updates, one change for useFetch and useAsyncData is pretty significant IMO - getCachedData. In this video, we will explore how that function can avoid superfluous calls to an API and cache data for visitors on the client, either until a hard-reload or...
Kuroro
Kuroro6mo ago
didn't see it was already answered! nice ❤️
Want results from more Discord servers?
Add your server