From 20853a89acc36172ce630ff594a39f94cc596d70 Mon Sep 17 00:00:00 2001 From: Italo Date: Thu, 12 Oct 2023 18:25:49 -0300 Subject: [PATCH] docs: add section about computed url for data fetching (#23605) --- docs/1.getting-started/6.data-fetching.md | 61 +++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/docs/1.getting-started/6.data-fetching.md b/docs/1.getting-started/6.data-fetching.md index eadd169e8b..4b8554da38 100644 --- a/docs/1.getting-started/6.data-fetching.md +++ b/docs/1.getting-started/6.data-fetching.md @@ -264,6 +264,67 @@ const { data, error, refresh } = await useFetch('/api/users', { }) ``` +Note that **watching a reactive value won't change the URL fetched**. For example, this will keep fetching the same initial ID of the user because the URL is constructed at the moment the function is invoked. + +```ts +const id = ref(1) + +const { data, error, refresh } = await useFetch(`/api/users/${id.value}`, { + watch: [id] +}) +``` + +If you need to change the URL based on a reactive value, you may want to use a [computed URL](#computed-url) instead. + +#### Computed URL + +Sometimes you may need to compute an URL from reactive values, and refresh the data each time these change. Instead of juggling your way around, you can attach each param as a reactive value. Nuxt will automatically use the reactive value and re-fetch each time it changes. + +```ts +const id = ref(null) + +const { data, pending } = useLazyFetch('/api/user', { + query: { + user_id: id + } +}) +``` + +In the case of more complex URL construction, you may use a callback as a [computed getter](https://vuejs.org/guide/essentials/computed.html) that returns the URL string. + +Every time a dependency changes, the data will be fetched using the newly constructed URL. Combine this with [not-immediate](#not-immediate), and you can wait until the reactive element changes before fetching. + +```vue + + + +``` + +If you need to force a refresh when other reactive values change, you can also [watch other values](#watch). + ### Not immediate The `useFetch` composable will start fetching data the moment is invoked. You may prevent this by setting `immediate: false`, for example, to wait for user interaction.