is it possible to fill pinia in server-side on nuxt 3? #947
-
import { defineStore } from 'pinia'
import axios from '@/utils/axios'
export const useTodos = defineStore('todos', {
state: () => ({
todo: {}
}),
actions: {
async fetch() {
const { data } = await axios.get('/todos/1')
this.todo = data
}
}
})
import { useTodos } from '@/store/todos'
const todos = useTodos()
todos.fetch() I am trying to replicate the |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 15 replies
-
my bad import { defineNuxtPlugin } from '#app'
import { useTodos } from '@/store/todos'
export default defineNuxtPlugin(async (nuxtApp) => {
const todos = useTodos(nuxtApp.$pinia)
await todos.fetch()
}) |
Beta Was this translation helpful? Give feedback.
-
Can you share the source code? i am having the same problem but haven't solved it yet. |
Beta Was this translation helpful? Give feedback.
-
✅ This is the way I've made it work Let's say in somewhere in your store you have a method Call that method in // layouts/default.vue
<script setup lang="ts">
import { useUserStore } from '~/store/user'
const userStore = useUserStore()
const { isLogged, initProfile } = userStore
// Init profile on server
if (isLogged) await useAsyncData('profile', initProfile)
</script> That way your high-level layout would always populate the store on the server-side ❗️The issue with this method would be that pages with <template>
<main>
<NuxtPage />
</main>
</template> That way you would ensure that all of the pages will call |
Beta Was this translation helpful? Give feedback.
-
Hello, I tried the above implementation, but the function in store is executed every time I click on a Does anyone have some ideas? I use |
Beta Was this translation helpful? Give feedback.
-
How can I do it with a nitro plugin (putting my code in |
Beta Was this translation helpful? Give feedback.
-
Hey, is this still possbile? i'm not being able to call composables inside plugins at all
|
Beta Was this translation helpful? Give feedback.
-
You can also use I have written an article on how to pass state from a prepare script to Nuxt. In a nutshell, you can import your prefetched data anywhere from the // `stores/todo.ts`
import { defineStore } from 'pinia'
import { todos } from '#nuxt-prepare'
export const useTodos = defineStore('todos', {
state: () => ({
todos: todos || [],
})
}) For the prepare script, see the docs. It basically boils down to: // `store.prepare.ts`
import { $fetch } from 'ofetch'
import { defineNuxtPrepareHandler } from '../src/config'
export default defineNuxtPrepareHandler(async () => {
const todos = await $fetch('todos/1', {
return {
// Pass your todos data to Nuxt and import it
// anywhere from `#nuxt-prepare`
state: {
todos,
},
}
}) |
Beta Was this translation helpful? Give feedback.
my bad