Skip to content

Commit

Permalink
fix: Make persistence work across navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanziness committed Apr 30, 2022
1 parent fb5168d commit df00dd7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 36 deletions.
10 changes: 6 additions & 4 deletions plugins/store-i18n-watch.client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
})
}
})
Expand Down
68 changes: 36 additions & 32 deletions plugins/store-persist.client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit df00dd7

Please sign in to comment.