0
# Data Fetching
1
2
Core composable for reactive data fetching with automatic caching, revalidation, and error handling using the stale-while-revalidate strategy.
3
4
## Capabilities
5
6
### useSWRV Hook
7
8
Main composable that provides reactive data fetching with caching.
9
10
```typescript { .api }
11
/**
12
* Vue composable for data fetching with stale-while-revalidate caching
13
* @param key - Unique identifier for the request (string, array, function, or reactive)
14
* @returns IResponse object with reactive data, error, loading states, and mutate function
15
*/
16
function useSWRV<Data = any, Error = any>(
17
key: IKey
18
): IResponse<Data, Error>;
19
20
/**
21
* Vue composable for data fetching with stale-while-revalidate caching
22
* @param key - Unique identifier for the request
23
* @param fn - Fetcher function that returns data or promise (null for cache-only, undefined for default fetcher)
24
* @param config - Configuration options
25
* @returns IResponse object with reactive data, error, loading states, and mutate function
26
*/
27
function useSWRV<Data = any, Error = any>(
28
key: IKey,
29
fn: fetcherFn<Data> | undefined | null,
30
config?: IConfig
31
): IResponse<Data, Error>;
32
```
33
34
**Usage Examples:**
35
36
```typescript
37
import useSWRV from "swrv";
38
39
// Basic usage with default fetch
40
const { data, error, isValidating } = useSWRV('/api/users');
41
42
// Custom fetcher function
43
const fetcher = (url) => axios.get(url).then(res => res.data);
44
const { data } = useSWRV('/api/users', fetcher);
45
46
// With configuration
47
const { data, error } = useSWRV('/api/users', fetcher, {
48
refreshInterval: 1000,
49
revalidateOnFocus: false
50
});
51
52
// Reactive key (dependent fetching)
53
const userId = ref(null);
54
const { data: user } = useSWRV(() => userId.value && `/api/users/${userId.value}`, fetcher);
55
56
// Array key for complex parameters
57
const { data } = useSWRV(['/api/search', { query: 'vue', page: 1 }],
58
([url, params]) => api.get(url, { params })
59
);
60
```
61
62
### Response Object Properties
63
64
The `IResponse` object returned by `useSWRV` contains reactive properties and methods.
65
66
```typescript { .api }
67
interface IResponse<Data = any, Error = any> {
68
/** Reactive reference to fetched data (undefined until first successful fetch) */
69
data: Ref<Data | undefined>;
70
/** Reactive reference to error object (undefined when no error) */
71
error: Ref<Error | undefined>;
72
/** Reactive reference indicating if currently revalidating data */
73
isValidating: Ref<boolean>;
74
/** Reactive reference indicating if initially loading (no cached data available) */
75
isLoading: Ref<boolean>;
76
/** Function to manually trigger revalidation with optional new data */
77
mutate: (data?: fetcherFn<Data>, opts?: revalidateOptions) => Promise<void>;
78
}
79
```
80
81
### Key Types
82
83
Flexible key system supporting various identifier patterns.
84
85
```typescript { .api }
86
/** Union type for cache key identifiers */
87
type IKey = keyType | WatchSource<keyType>;
88
89
/** Basic key types supported */
90
type keyType = string | any[] | null | undefined;
91
```
92
93
**Key Examples:**
94
95
```typescript
96
// String key
97
useSWRV('/api/users');
98
99
// Array key (serialized to stable string)
100
useSWRV(['/api/users', { active: true, limit: 10 }]);
101
102
// Function key (reactive, watched for changes)
103
useSWRV(() => user.value ? `/api/users/${user.value.id}/posts` : null);
104
105
// Ref key (reactive)
106
const endpoint = ref('/api/users');
107
useSWRV(endpoint);
108
109
// Conditional key (null disables fetching)
110
useSWRV(isAuthenticated.value ? '/api/profile' : null);
111
```
112
113
### Fetcher Function
114
115
Function responsible for data fetching logic.
116
117
```typescript { .api }
118
/**
119
* Function that fetches data for a given key
120
* @param args - Arguments passed from the key (single value for string keys, spread array for array keys)
121
* @returns Data directly or Promise resolving to data
122
*/
123
type fetcherFn<Data> = (...args: any) => Data | Promise<Data>;
124
```
125
126
**Fetcher Examples:**
127
128
```typescript
129
// Default fetch API
130
const defaultFetcher = (url) => fetch(url).then(res => res.json());
131
132
// Axios fetcher
133
const axiosFetcher = (url) => axios.get(url).then(res => res.data);
134
135
// Custom fetcher with error handling
136
const customFetcher = async (url, options = {}) => {
137
const response = await fetch(url, {
138
headers: { 'Authorization': `Bearer ${getToken()}` },
139
...options
140
});
141
142
if (!response.ok) {
143
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
144
}
145
146
return response.json();
147
};
148
149
// Fetcher for array keys
150
const searchFetcher = ([endpoint, params]) =>
151
fetch(`${endpoint}?${new URLSearchParams(params)}`).then(res => res.json());
152
```
153
154
### Configuration Options
155
156
Comprehensive configuration for customizing swrv behavior.
157
158
```typescript { .api }
159
interface IConfig<Data = any, Fn extends fetcherFn<Data> = fetcherFn<Data>> {
160
/** Polling interval in milliseconds (0 disables polling) */
161
refreshInterval?: number;
162
/** Cache implementation to use */
163
cache?: LocalStorageCache | SWRVCache<any>;
164
/** Time window in ms to deduplicate identical requests */
165
dedupingInterval?: number;
166
/** Time to live for cache entries in milliseconds (0 = no expiration) */
167
ttl?: number;
168
/** Server-side time to live in milliseconds */
169
serverTTL?: number;
170
/** Automatically revalidate when window regains focus */
171
revalidateOnFocus?: boolean;
172
/** Debounce revalidation by this many milliseconds */
173
revalidateDebounce?: number;
174
/** Retry requests when they fail */
175
shouldRetryOnError?: boolean;
176
/** Interval between error retries in milliseconds */
177
errorRetryInterval?: number;
178
/** Maximum number of error retries */
179
errorRetryCount?: number;
180
/** Default fetcher function to use when none provided */
181
fetcher?: Fn;
182
/** Function to check online status */
183
isOnline?: () => boolean;
184
/** Function to check if document is visible */
185
isDocumentVisible?: () => boolean;
186
}
187
```
188
189
**Configuration Examples:**
190
191
```typescript
192
// Polling configuration
193
const { data } = useSWRV('/api/stats', fetcher, {
194
refreshInterval: 5000, // Poll every 5 seconds
195
revalidateOnFocus: false // Don't revalidate on focus during polling
196
});
197
198
// Error handling configuration
199
const { data, error } = useSWRV('/api/flaky-endpoint', fetcher, {
200
shouldRetryOnError: true,
201
errorRetryCount: 3,
202
errorRetryInterval: 1000 // 1 second between retries
203
});
204
205
// Performance optimization
206
const { data } = useSWRV('/api/heavy-data', fetcher, {
207
dedupingInterval: 10000, // Dedupe for 10 seconds
208
revalidateDebounce: 500, // Debounce rapid revalidations
209
ttl: 300000 // Cache for 5 minutes
210
});
211
```
212
213
### Revalidation Options
214
215
Options for controlling manual revalidation behavior.
216
217
```typescript { .api }
218
interface revalidateOptions {
219
/** Whether to retry on error for this revalidation */
220
shouldRetryOnError?: boolean;
221
/** Current error retry count (internal use) */
222
errorRetryCount?: number;
223
/** Force revalidation even if within deduping interval */
224
forceRevalidate?: boolean;
225
}
226
```
227
228
**Manual Revalidation Examples:**
229
230
```typescript
231
const { data, mutate } = useSWRV('/api/users', fetcher);
232
233
// Revalidate with current fetcher
234
await mutate();
235
236
// Optimistic update then revalidate
237
await mutate(async () => {
238
const newUser = await createUser(userData);
239
return [...data.value, newUser];
240
});
241
242
// Force revalidation (ignore deduping)
243
await mutate(undefined, { forceRevalidate: true });
244
245
// Revalidate without error retry
246
await mutate(undefined, { shouldRetryOnError: false });
247
```