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​
- JavaScript
- TypeScript
// 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)
})
}
// store.ts
import { cervello } from '@cervello/react'
import type { UseFunction } from '@cervello/react'
const { store } = cervello(() => {
const themeValue = localStorage.getItem('theme') ?? 'dark'
return {
theme: themeValue,
user: null,
}
}).use(persistTheme)
const persistTheme: UseFunction<typeof store> = ({ onPartialChange }): void => {
onPartialChange(['theme'], (store) => {
localStorage.setItem('theme', store.theme)
})
}