Pinia Network Store Fix
April 18, 2025 · AI Conversations
import { ref, onMounted, onBeforeUnmount } from 'vue'
export const useNetworkStore = defineStore('network', () => {
const isOnline = ref(navigator.onLine)
// ✅ Define handlers outside so they can be removed later
const handleOnline = () => (isOnline.value = true)
const handleOffline = () => (isOnline.value = false)
onMounted(() => {
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
})
onBeforeUnmount(() => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
})
return { isOnline }
})
this code always return online even internet is off
In a **Pinia store**, you should use `onMounted`-like logic directly in the store's setup function (i.e., when the store is initialized), and you must **manually clean up** when needed (though it's rarely required for global stores).
—
### ✅ Corrected Version for Pinia Store
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useNetworkStore = defineStore('network', () => {
const isOnline = ref(navigator.onLine)
const handleOnline = () => (isOnline.value = true)
const handleOffline = () => (isOnline.value = false)
// Add listeners immediately when store is initialized
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
// Optional: add cleanup method if needed
const cleanup = () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
}
return { isOnline, cleanup }
})
### 🔍 Why Your Version Didn’t Work
– `onMounted()` and `onBeforeUnmount()` are tied to Vue component lifecycle.
– A Pinia store doesn’t have a component lifecycle — it gets created once and persists as a singleton.
—
### ✅ Usage in Component
In your Vue component, just do:
const network = useNetworkStore()
console.log(network.isOnline)
Let me know if you want to auto-reconnect or notify the user when network goes offline.