Reputation: 1
I'm trying to create a pinia store that load data in SSR. How to load data in SSR in a pinia store ? Is that possible ?
I'd like to be able to do something like this in every component where i'll need the data :
const myStore = useMyStore();
myStore.fetchItems();
And this is my store :
import { defineStore } from 'pinia';
export const useMyStore = defineStore('myStore', {
state: () => ({
items: ref([]),
loading: ref(false),
error: ref(null)
}),
actions: {
async fetchItems() {
if (this.items?.length > 0) {
return;
}
this.loading = true;
const { $appConfig } = useNuxtApp();
const apiUrl = $appConfig.api?.url;
try {
const data = await $fetch(`${apiUrl}/reference-data/airports/`);
this.items = data;
} catch (err) {
this.error = err;
} finally {
this.loading = false;
}
}
},
persist: {
storage: piniaPluginPersistedstate.sessionStorage()
}
});
For now, i see the api call in network tab on first load, but when i try to refresh, i get in the console :
Hydration completed but contains mismatches.
Why is that ? What's the best way to load data that will be accross the app in SSR ?
Upvotes: 0
Views: 16
Reputation: 164
You should not use ref()
in the state object.
import { defineStore } from 'pinia';
export const useMyStore = defineStore('myStore', {
state: () => ({
items: [],
loading: false,
error: null
}),
actions: {
async fetchItems() {
if (this.items?.length > 0) {
return;
}
this.loading = true;
const { $appConfig } = useNuxtApp();
const apiUrl = $appConfig.api?.url;
try {
const data = await $fetch(`${apiUrl}/reference-data/airports/`);
this.items = data;
} catch (err) {
this.error = err;
} finally {
this.loading = false;
}
}
},
persist: {
storage: piniaPluginPersistedstate.sessionStorage()
}
});
Upvotes: 0