There is no silver bullet to data fetching because of the different data fetching strategies and how they can define the architecture of the application and its UX. However, I think it's possible to find a solution that is flexible enough to promote good practices and reduce the complexity of data fetching in applications.
That is the goal of this RFC, to standardize and improve data fetching with vue-router:
Automatically integrate fetching to the navigation cycle (or not by making it lazy/non-blocking)
Automatically rerun when used params/query params/hash changes (avoid unnecessary fetches)
Basic client-side caching with time-based expiration to only fetch once per navigation while using it anywhere
Provide control over loading/error states
Allow parallel or sequential data fetching (loaders that use each other)
<script lang="ts">
import { getUserById } from '../api'
import { defineLoader } from 'vue-router'
// name the loader however you want **and export it**
export const useUserData = defineLoader(async (route) => {
const user = await getUserById(route.params.id)
// ...
// return anything you want to expose
return user
})
// Optional: define other component options
export default defineComponent({
name: 'custom-name',
inheritAttrs: false
})
</script>
<script lang="ts" setup>
// find the user as `data` and some other properties
const { data: user, pending, error, refresh } = useUserData()
// data is always present, pending changes when going from '/users/2' to '/users/3'
</script>
Important: Do NOT comment on this PR. Please use the discussion thread linked above to provide feedback, as it provides branched discussions that are easier to follow. This also makes the edit history of the PR clearer.
Summary
There is no silver bullet to data fetching because of the different data fetching strategies and how they can define the architecture of the application and its UX. However, I think it's possible to find a solution that is flexible enough to promote good practices and reduce the complexity of data fetching in applications. That is the goal of this RFC, to standardize and improve data fetching with vue-router:
Links
Important: Do NOT comment on this PR. Please use the discussion thread linked above to provide feedback, as it provides branched discussions that are easier to follow. This also makes the edit history of the PR clearer.