Skip to content

Commit

Permalink
Fix Pinia/useLocalStorage in SSR mode.
Browse files Browse the repository at this point in the history
  • Loading branch information
krazkidd committed Sep 26, 2023
1 parent 2915eb7 commit 08d60b9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 38 deletions.
6 changes: 2 additions & 4 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ export default defineNuxtConfig({
"@vueuse/nuxt",
"nuxt-vuefire"
],
// NOTE: We have to disable SSR until Pinia has better
// support for our usage. (See stores/*.ts.)
// HACK: We have to disable SSR until Pinia has better
// support for our usage. See stores/AppSettings.ts.
// NOTE: This allows us to deploy to some free
// hosting services.
ssr: false,
css: [
'primevue/resources/themes/saga-blue/theme.css',
Expand Down
40 changes: 6 additions & 34 deletions stores/Team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,17 @@ import { nanoid } from "nanoid";

import type { ID } from '~~/types';

// NOTE: This Pinia store requires `ssr: false` in `nuxt.config.*` because the server
// will try to serialize our computed state properties to JSON, and that will fail
// because functions can't be serialized.
//
// See: [The Pinia guide](https://pinia.vuejs.org/core-concepts/)
// https://github.com/vuejs/pinia/issues/829 (look for "Advanced SSR")
// https://github.com/vuejs/pinia/issues/447#issuecomment-1455285437
// https://github.com/nuxt/nuxt/issues/20889

export const useTeamStore = defineStore('TeamStore', {
state: () => {
const _id = useLocalStorage<ID>('TeamStore:id', nanoid());
const _isLocked = useLocalStorage<boolean>('TeamStore:isLocked', false);

// NOTE: We provide setters so we can persist to storage.
// Source: https://github.com/vuejs/pinia/issues/447#issuecomment-1455285437

const id = computed<ID>({
get: () => _id.value,
set: (v) => _id.value = v
});

const isLocked = computed<boolean>({
get: () => _isLocked.value,
set: (v) => _isLocked.value = v
});

// function $reset() {
// //TODO
// }

return {
id,

isLocked,

//$reset,
id: useLocalStorage<ID>('TeamStore:id', nanoid()),
isLocked: useLocalStorage<boolean>('TeamStore:isLocked', false),
};
},
hydrate(state, initialState) {
state.id = useLocalStorage<ID>('TeamStore:id', initialState.id).value,
state.isLocked = useLocalStorage<boolean>('TeamStore:isLocked', initialState.isLocked).value
},
});

if (import.meta.hot) {
Expand Down

0 comments on commit 08d60b9

Please sign in to comment.