0
# Global State Management
1
2
Global mutation function and cross-component data synchronization for coordinating cache updates across all swrv instances.
3
4
## Capabilities
5
6
### Global Mutate Function
7
8
Updates cache globally and triggers revalidation across all components using the same key.
9
10
```typescript { .api }
11
/**
12
* Global function to mutate cache data and trigger revalidation across all swrv instances
13
* @param key - Cache key to update
14
* @param res - New data or Promise resolving to new data
15
* @param cache - Cache instance to update (defaults to global cache)
16
* @param ttl - Time to live for the cached data (defaults to config ttl)
17
* @returns Promise resolving to the new cache data object
18
*/
19
function mutate<Data>(
20
key: string,
21
res: Promise<Data> | Data,
22
cache?: SWRVCache<any>,
23
ttl?: number
24
): Promise<{data: Data, error: any, isValidating: boolean}>;
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { mutate } from "swrv";
31
32
// Update cache with new data
33
await mutate('/api/users', newUsersList);
34
35
// Update cache with promise
36
await mutate('/api/users', fetch('/api/users').then(res => res.json()));
37
38
// Optimistic update
39
await mutate('/api/users', [...existingUsers, newUser]);
40
41
// Update specific cache instance
42
const customCache = new SWRVCache();
43
await mutate('/api/data', newData, customCache);
44
45
// Update with custom TTL
46
await mutate('/api/temp-data', tempData, undefined, 5000); // 5 second TTL
47
```
48
49
### Prefetching Data
50
51
Load data into cache before components request it, improving perceived performance.
52
53
**Prefetching Examples:**
54
55
```typescript
56
import { mutate } from "swrv";
57
58
// Prefetch on hover
59
function prefetchUser(userId) {
60
mutate(
61
`/api/users/${userId}`,
62
fetch(`/api/users/${userId}`).then(res => res.json())
63
);
64
}
65
66
// Prefetch in route guards
67
router.beforeEach(async (to) => {
68
if (to.name === 'user-profile') {
69
await mutate(
70
`/api/users/${to.params.id}`,
71
userApi.getUser(to.params.id)
72
);
73
}
74
});
75
76
// Batch prefetch related data
77
async function prefetchDashboardData() {
78
await Promise.all([
79
mutate('/api/stats', statsApi.getStats()),
80
mutate('/api/notifications', notificationApi.getRecent()),
81
mutate('/api/user/profile', userApi.getCurrentUser())
82
]);
83
}
84
```
85
86
### Cross-Component Synchronization
87
88
Automatically synchronize data across multiple components using the same cache key.
89
90
**Synchronization Examples:**
91
92
```typescript
93
// Component A - Updates user data
94
export default {
95
setup() {
96
const { data: user, mutate: updateUser } = useSWRV('/api/user/profile', fetcher);
97
98
const saveProfile = async (updates) => {
99
// Optimistic update - immediately visible in all components
100
await updateUser(async () => {
101
const updated = { ...user.value, ...updates };
102
await userApi.updateProfile(updates);
103
return updated;
104
});
105
};
106
107
return { user, saveProfile };
108
}
109
};
110
111
// Component B - Automatically receives updates
112
export default {
113
setup() {
114
// Automatically syncs with Component A's updates
115
const { data: user } = useSWRV('/api/user/profile', fetcher);
116
117
return { user };
118
}
119
};
120
121
// Component C - Also automatically synced
122
export default {
123
setup() {
124
// All three components share the same cache entry
125
const { data: user } = useSWRV('/api/user/profile', fetcher);
126
127
return { user };
128
}
129
};
130
```
131
132
### Cache-Only Mode
133
134
Serve data exclusively from cache without triggering network requests.
135
136
```typescript { .api }
137
/**
138
* Cache-only fetching by passing null as fetcher
139
* Useful when you know data is already cached by another component
140
*/
141
useSWRV(key, null); // null fetcher = cache-only mode
142
```
143
144
**Cache-Only Examples:**
145
146
```typescript
147
// Main component fetches data
148
const MainComponent = {
149
setup() {
150
const { data } = useSWRV('/api/config', fetcher);
151
return { data };
152
}
153
};
154
155
// Child components use cache-only mode
156
const ChildComponent = {
157
setup() {
158
// Only retrieve from cache, no network request
159
const { data } = useSWRV('/api/config', null);
160
return { data };
161
}
162
};
163
164
// Conditional cache-only mode
165
const ConditionalComponent = {
166
setup() {
167
const isOnline = ref(navigator.onLine);
168
169
// Use cache-only when offline
170
const { data } = useSWRV('/api/data', isOnline.value ? fetcher : null);
171
172
return { data };
173
}
174
};
175
```
176
177
### Error Propagation
178
179
Errors from global mutations are propagated to all components using the same key.
180
181
**Error Handling Examples:**
182
183
```typescript
184
import { mutate } from "swrv";
185
186
// Error handling in global mutation
187
try {
188
await mutate('/api/users', fetch('/api/users').then(res => {
189
if (!res.ok) throw new Error(`HTTP ${res.status}`);
190
return res.json();
191
}));
192
} catch (error) {
193
console.error('Global mutation failed:', error);
194
// Error will appear in all components using '/api/users'
195
}
196
197
// Component error handling
198
export default {
199
setup() {
200
const { data, error } = useSWRV('/api/users', fetcher);
201
202
// Watch for errors (including from global mutations)
203
watch(error, (newError) => {
204
if (newError) {
205
showErrorNotification(newError.message);
206
}
207
});
208
209
return { data, error };
210
}
211
};
212
```
213
214
### State Management Integration
215
216
Integrate swrv with Vuex or other state management solutions.
217
218
**Vuex Integration Examples:**
219
220
```typescript
221
// Vuex store actions
222
const store = createStore({
223
actions: {
224
async updateUser({ commit }, userData) {
225
// Update both Vuex and swrv cache
226
commit('SET_USER', userData);
227
await mutate('/api/user', userData);
228
},
229
230
async syncUserFromServer({ commit }) {
231
// Fetch fresh data and update both stores
232
const user = await fetch('/api/user').then(res => res.json());
233
commit('SET_USER', user);
234
await mutate('/api/user', user);
235
}
236
}
237
});
238
239
// Component using both Vuex and swrv
240
export default {
241
setup() {
242
const store = useStore();
243
const { data: swrvUser } = useSWRV('/api/user', fetcher);
244
245
// Sync Vuex when swrv data changes
246
watch(swrvUser, (newUser) => {
247
if (newUser) {
248
store.commit('SET_USER', newUser);
249
}
250
});
251
252
return {
253
user: computed(() => store.state.user),
254
swrvUser
255
};
256
}
257
};
258
```
259
260
### Memory Management
261
262
Automatic cleanup of cached references when components unmount.
263
264
**Cleanup Examples:**
265
266
```typescript
267
// Automatic cleanup - no manual intervention needed
268
export default {
269
setup() {
270
const { data } = useSWRV('/api/data', fetcher);
271
272
// swrv automatically cleans up internal references
273
// when this component unmounts
274
275
return { data };
276
}
277
};
278
279
// Manual cache cleanup if needed
280
import { mutate } from "swrv";
281
282
export default {
283
setup() {
284
const { data } = useSWRV('/api/temp-data', fetcher);
285
286
onUnmounted(() => {
287
// Manually clear cache entry if needed
288
mutate('/api/temp-data', undefined);
289
});
290
291
return { data };
292
}
293
};
294
```