#useFetch refresh data over multiple components

3 messages · Page 1 of 1 (latest)

hasty radishBOT
#

Hi @humble jacinth. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

refreshNuxtData is used to refetch all or specific asyncData instances, including those from useAsyncData, useLazyAsyncData, useFetch, and useLazyFetch. 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 asyncData instance, it is recommended to use its refresh or execute method 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.

So your approach of using refreshNuxtData('me') is the correct solution for your use case.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: