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'
+import { createPinia } from 'pinia'
// retrieve the rootState server side
const pinia = createPinia()
const app = createApp(App)
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
+// serialize, escape (VERY important if the content of the state can be changed
+// by the user, which is almost always the case), and place it somewhere on
+// the page, for example, as a global variable.
+JSON.stringify(pinia.state.value)
```
-On client side, you must tell pinia how to read that variable:
+On client side, you must hydrate pinia's state before calling any `useStore()` function. For example, if we serialize the state into a `<script>` tag to make it accessible globally on client side through `window.__pinia`, we can write this:
```js
-import { setStateProvider } from 'pinia'
+const pinia = createPinia()
+const app = createApp(App)
+app.use(pinia)
-// if the previous step appended a script to the page that sets a global variable named `__pinia` with the rootState
-setStateProvider(() => window.__pinia)
+// must be set by the user
+if (isClient) {
+ pinia.state.value = JSON.parse(window.__pinia)
+}
```
### Composing Stores
-import { createPinia, defineStore, getRootState } from '../src'
+import { createPinia, defineStore } from '../src'
describe('Root State', () => {
const useA = defineStore({
})
it('works with no stores', () => {
- expect(getRootState(createPinia())).toEqual({})
+ expect(createPinia().state.value).toEqual({})
})
it('retrieves the root state of one store', () => {
const pinia = createPinia()
useA(pinia)
- expect(getRootState(pinia)).toEqual({
+ expect(pinia.state.value).toEqual({
a: { a: 'a' },
})
})
const pinia2 = createPinia()
useA(pinia1)
useB(pinia2)
- expect(getRootState(pinia1)).toEqual({
+ expect(pinia1.state.value).toEqual({
a: { a: 'a' },
})
- expect(getRootState(pinia2)).toEqual({
+ expect(pinia2.state.value).toEqual({
b: { b: 'b' },
})
})
const pinia1 = createPinia()
useA(pinia1)
useB(pinia1)
- expect(getRootState(pinia1)).toEqual({
+ expect(pinia1.state.value).toEqual({
a: { a: 'a' },
b: { b: 'b' },
})
/**
* Gets the root state of all active stores. This is useful when reporting an application crash by
* retrieving the problematic state and send it to your error tracking service.
+ *
* @param pinia - application's pinia
*/
export function getRootState(pinia: Pinia): Record<string, StateTree> {