From 30f30fb9f8bd6d453d0c747eed390dc1f56bcb02 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Tue, 29 Sep 2020 11:07:03 +0200 Subject: [PATCH] docs: hydration for ssr --- README.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c57a5f0c..1ea5ac0e 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,7 @@ main.state = { counter: 666, name: 'Paimon' } ### SSR -Pinia should work out of the box for SSR as long as you call your `useStore()` functions at the top of `setup` functions, `getters` and `actions`: +Creating stores with Pinia should work out of the box for SSR as long as you call your `useStore()` functions at the top of `setup` functions, `getters` and `actions`: ```ts export default defineComponent({ @@ -287,6 +287,29 @@ router.beforeEach((to) => { }) ``` +To hydrate the initial state, you need to make sure the rootState is included somewhere in the HTML for Pinia to pick it up later on: + +```js +import { createPinia, getRootState } from 'pinia' +// retrieve the rootState server side +const pinia = createPinia() +const app = createApp(App) +app.use(router) +app.use(pinia) + +// after rendering the page, the root state is build and can be read +getRootState() // serialize, escape, and place it somewhere on the page, for example, as a global variable +``` + +On client side, you must tell pinia how to read that variable: + +```js +import { setStateProvider } from 'pinia' + +// if the previous step appended a script to the page that sets a global variable named `__pinia` with the rootState +setStateProvider(() => window.__pinia) +``` + ### Composing Stores Composing stores may look hard at first glance but there is only one rule to follow really: -- 2.47.2