#useFetch and refresh from multiple files
1 messages · Page 1 of 1 (latest)
To refresh data fetched with useFetch from multiple files in Nuxt, you should use an explicit key for your fetch call. This allows you to access and refresh the same data instance from anywhere in your app using the key. Here’s how you can do it:
- Provide a key in your composable:
export const useBadges = () => {
const { data, pending, refresh } = useFetch<DatabaseBadge[]>('/api/badges/check', {
key: 'badges'
});
return {
gotBadges: data,
pendingGotBadges: pending,
refreshGotBadges: refresh,
};
};
- Refresh from anywhere using the key:
You can use the refreshNuxtData utility to refresh the data by its key from any file:
import { refreshNuxtData } from '#app'
await refreshNuxtData('badges')
This will trigger a refresh of the data associated with the 'badges' key, regardless of where the original useFetch was called. This approach is recommended for shared or global data that needs to be refreshed from multiple places in your application.
References:
- useFetch API: Keys and shared state
- refreshNuxtData utility
- useNuxtData for accessing cached data by key
This pattern ensures your data is consistent and easily refreshable across your Nuxt app.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@dreamy knoll Kapa.ai is still learning and improving, please let me know how I did by reacting below.
the problem is that when I call useBadges from multiple files, it does run the useFetch multiple times