Pinia Network Store Fix

User
import { defineStore } from 'pinia'
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

Assistant
You're encountering this issue because the lifecycle hooks `onMounted` and `onBeforeUnmount` are **only effective inside Vue components**, not inside a Pinia store.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *