Skip to main content

Persist on localStorage

Description​

This is an example where you can store in local-storage (it could be any other place as cookies) the theme selected by the user in case he/she wants to change it.
Then on initialization of the store, we get the theme from local-storage and set it as the current theme.

Example​

// store.js
import { cervello } from '@cervello/react'

const { store } = cervello(() => {
const themeValue = localStorage.getItem('theme') ?? 'dark'

return {
theme: themeValue,
user: null,
}
}).use(persistTheme)


const persistTheme = ({ onPartialChange }) => {
onPartialChange(['theme'], (store) => {
localStorage.setItem('theme', store.theme)
})
}