Network Offline Caching Vue
March 14, 2025 · AI Conversations
### 1. **Detect Network Failure**
You can use the `navigator.onLine` property or catch Axios errors to determine if the network is down.
### 2. **Use LocalStorage or IndexedDB for Caching**
Store fetched API results in `localStorage` or `IndexedDB` so that they can be used when offline.
### 3. **Fallback to Cached Data**
If a network request fails, retrieve and display the last cached data.
—
## Implementation:
### **1. Use Axios with Cache Handling**
Modify your Axios request to store and retrieve cached responses.
<template>
<div>
<h2>Data</h2>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Network error! Showing cached data.</div>
<ul v-if="data.length">
<li v-for="item in data" :key="item.id">{{ item.name }}</li>
</ul>
<div v-else>No data available.</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
data: [],
loading: true,
error: false,
};
},
mounted() {
this.fetchData();
},
methods: {
async fetchData() {
const cacheKey = "cachedData";
const apiUrl = "https://api.example.com/data"; // Replace with your API endpoint
if (!navigator.onLine) {
this.loadCachedData(cacheKey);
return;
}
try {
const response = await axios.get(apiUrl);
this.data = response.data;
localStorage.setItem(cacheKey, JSON.stringify(this.data)); // Cache data
this.error = false;
} catch (err) {
console.error("Network error:", err);
this.error = true;
this.loadCachedData(cacheKey);
} finally {
this.loading = false;
}
},
loadCachedData(cacheKey) {
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
this.data = JSON.parse(cachedData);
}
this.loading = false;
},
},
};
</script>
—
## **Alternative: Using Vuex/Pinia for Global State Management**
If you are using Vuex or Pinia, you can store API results globally and retrieve them when needed.
—
## **Additional Enhancements**
1. **Service Workers**: Use a service worker to cache API requests for better offline support.
2. **IndexedDB**: Use `idb` library for more persistent caching.
3. **Toast Notification**: Show a message when switching between online and offline modes.
Would you like me to add a service worker setup for offline caching?
—
### **1. NetworkStatus.vue (Reusable Component)**
<template>
<div v-if="!isOnline" class="network-alert">
⚠️ You are offline. Some features may not be available.
</div>
</template>
<script>
export default {
data() {
return {
isOnline: navigator.onLine
};
},
mounted() {
window.addEventListener("online", this.updateNetworkStatus);
window.addEventListener("offline", this.updateNetworkStatus);
},
beforeUnmount() {
window.removeEventListener("online", this.updateNetworkStatus);
window.removeEventListener("offline", this.updateNetworkStatus);
},
methods: {
updateNetworkStatus() {
this.isOnline = navigator.onLine;
}
}
};
</script>
<style scoped>
.network-alert {
position: fixed;
top: 0;
width: 100%;
background: red;
color: white;
text-align: center;
padding: 10px;
font-weight: bold;
z-index: 1000;
}
</style>
—
### **2. Use It in App.vue or Any Component**
Simply include the component in your `App.vue` or any other component.
<template>
<NetworkStatus />
<router-view />
</template>
<script>
import NetworkStatus from "@/components/NetworkStatus.vue";
export default {
components: {
NetworkStatus
}
};
</script>
—
### **3. How It Works**
– Detects if the user is offline using `navigator.onLine`.
– Displays a red warning bar when the network is lost.
– Listens for the `online` and `offline` events to update the UI dynamically.
Would you like me to integrate a service worker for **progressive caching** when offline?
—
### **1. NetworkStatus.vue (Composition API)**
<template>
<div v-if="!isOnline" class="network-alert">
⚠️ You are offline. Some features may not be available.
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
const isOnline = ref(navigator.onLine);
const updateNetworkStatus = () => {
isOnline.value = navigator.onLine;
};
onMounted(() => {
window.addEventListener("online", updateNetworkStatus);
window.addEventListener("offline", updateNetworkStatus);
});
onUnmounted(() => {
window.removeEventListener("online", updateNetworkStatus);
window.removeEventListener("offline", updateNetworkStatus);
});
</script>
<style scoped>
.network-alert {
position: fixed;
top: 0;
width: 100%;
background: red;
color: white;
text-align: center;
padding: 10px;
font-weight: bold;
z-index: 1000;
}
</style>
—
### **2. Use It in App.vue or Any Component**
Include the component in `App.vue` or another layout.
<template>
<NetworkStatus />
<router-view />
</template>
<script setup>
import NetworkStatus from "@/components/NetworkStatus.vue";
</script>
—
### **How It Works**
– Uses `ref` to track network status (`isOnline`).
– Detects `online` and `offline` events with `window.addEventListener()`.
– Updates state dynamically when the network connection changes.
– Cleans up event listeners when the component unmounts.
Let me know if you need enhancements like **auto-retry for API requests** when the network restores! 🚀