#useFetch refresh data over multiple components
3 messages · Page 1 of 1 (latest)
You're encountering a common issue with useFetch in Nuxt when using it inside a custom composable across multiple components.
The problem is that when you wrap useFetch in a custom function like this, each component that calls your composable gets its own isolated instance of useFetch. This is why refreshing in one component doesn't update the data in other components.
This behavior is documented in a Stack Overflow post where someone experienced the same issue:
"This made me realize that composables are not as isolated as I thought when using useFetch, or maybe I'm doing something very wrong. Because it looks like both component were calling to the same unisolated function at the same time even if said function are supposed to be isolated." Stack Overflow Post
The solution is to use refreshNuxtData as you've discovered. This is actually the recommended approach for refreshing data across multiple components. From the Nuxt documentation:
refreshNuxtDatais used to refetch all or specificasyncDatainstances, including those fromuseAsyncData,useLazyAsyncData,useFetch, anduseLazyFetch. Nuxt Documentation
You can refresh specific data by passing the key:
await refreshNuxtData('me')
While the docs do mention that using the refresh method from the composable is a preferred way, that's specifically when you have access to the same instance:
If you have access to the
asyncDatainstance, it is recommended to use itsrefreshorexecutemethod as the preferred way to refetch the data. Nuxt Documentation
But in your case, since you're dealing with multiple components using the same data, refreshNuxtData is the correct approach.
There's also a common mistake when wrapping useFetch in custom functions, as highlighted in a YouTube video by Alexander Lichter titled "You are using useFetch WRONG!" which discusses this exact issue of wrapping useFetch in functions and the problems it can cause with reactivity and caching.