LocalStorage
You may store the content of your reducers in LocalStorage with the kea-localstorage
plugin.
Installation
First install the kea-localstorage
package:
yarn add kea-localstorage
npm install --save kea-localstorage
Then you have a few ways to install the plugin globally for all logic stores:
// the cleanest way
import localStoragePlugin from 'kea-localstorage'
import { getStore } from 'kea'
const store = getStore({
plugins: [ localStoragePlugin ]
})
// another way
import localStoragePlugin from 'kea-localstorage'
import { activatePlugin } from 'kea'
activatePlugin(localStoragePlugin)
// the shortest way
import 'kea-localstorage/install'
Use whichever way is most convenient for your setup.
Alternatively you may skip installing it globally and only include in the logic stores that need it
import { kea } from 'kea'
import localStoragePlugin from 'kea-thunk'
const logic = kea({
plugins: [
localStoragePlugin
],
// actions, reducers, etc
})
Usage
To make a reducer persist in LocalStorage, your logic store must have a defined path
.
Just add { persist: true }
as an option to your reducers, and it will be stored:
const logic = kea({
// path must be defined!
path: () => ['scenes', 'homepage', 'name'],
actions: ({ constants }) => ({
updateName: name => ({ name })
}),
reducers: ({ actions, constants }) => ({
// just add { persist: true }
name: ['chirpy', PropTypes.string, { persist: true }, {
[actions.updateName]: (state, payload) => payload.name
}]
})
})
Example
Update the counter and refresh the page. The number should remain:
Note: if you refresh, it may flash the number 0 for a brief moment, as that's what's stored in the pre-rendered HTML that's served when you open the page. It should then immediately update.