diff --git a/plugins/store-i18n-watch.client.js b/plugins/store-i18n-watch.client.js index 7828760..f9e8188 100644 --- a/plugins/store-i18n-watch.client.js +++ b/plugins/store-i18n-watch.client.js @@ -7,10 +7,12 @@ const NuxtI18nWatcherPlugin = ({ app, $pinia }) => { store.$state.lang = app.i18n.locale } - store.$subscribe(() => { - if (store.$state.lang) { - app.i18n.setLocale(store.$state.lang) - } + app.router.afterEach(() => { + store.$subscribe(() => { + if (store.$state.lang) { + app.i18n.setLocale(store.$state.lang) + } + }) }) } }) diff --git a/plugins/store-persist.client.js b/plugins/store-persist.client.js index 1de92ff..973db9d 100644 --- a/plugins/store-persist.client.js +++ b/plugins/store-persist.client.js @@ -13,42 +13,46 @@ function restoreStore (store) { } } -function PiniaPersistPlugin ({ store }) { - if (persistStores.includes(store.$id)) { - const restore = localStorage.getItem(storeResetKey) == null - // Restore the store first - if (restore) { - restoreStore(store) - } +const PiniaNuxtPersistencePlugin = ({ app, $pinia }) => { + const PiniaPersistPlugin = ({ store }) => { + if (persistStores.includes(store.$id)) { + const restore = localStorage.getItem(storeResetKey) == null + // Restore the store first + if (restore) { + restoreStore(store) + } - // Subscribe to changes and persist them - const unsubscribe = store.$subscribe(() => { - try { - if (store.$id === 'settings') { - if (store.$state.reset) { - // if the settings store is in reset state, set store reset key - localStorage.setItem(storeResetKey, '1') - } else { - // otherwise remove the reset key - localStorage.removeItem(storeResetKey) + // `afterEach` is used as a workaround to Pinia subscribers disappearing on navigation + app.router.afterEach(() => { + // Subscribe to changes and persist them + const unsubscribe = store.$subscribe(() => { + try { + if (store.$id === 'settings') { + if (store.$state.reset) { + // if the settings store is in reset state, set store reset key + localStorage.setItem(storeResetKey, '1') + } else { + // otherwise remove the reset key + localStorage.removeItem(storeResetKey) + } + } + + // otherwise persist store + localStorage.setItem( + getStorePersistenceKey(store.$id), + JSON.stringify(store.$state) + ) + } catch (err) { + console.log(err) + // Failed to write to localStorage for some reason, unsubscribe persistence + unsubscribe() } - } - - // otherwise persist store - localStorage.setItem( - getStorePersistenceKey(store.$id), - JSON.stringify(store.$state) - ) - } catch (err) { - // Failed to write to localStorage for some reason, unsubscribe persistence - unsubscribe() - } - }) + }) + }) + } } -} -const PiniaNuxtPlugin = ({ $pinia }) => { $pinia.use(PiniaPersistPlugin) } -export default PiniaNuxtPlugin +export default PiniaNuxtPersistencePlugin