Save MobX state in LocalStorage #2798
-
Originally, I had my store working when I was using context.tsimport React from 'react'
import { stores, PersistState, CounterStore } from '@/store/index'
import type { ICounterStore } from '@/types/index'
export const FrameItContext = React.createContext<ICounterStore>(new CounterStore())
export const useCounterStore = () => React.useContext(FrameItContext) Then I started using Mobx Persist Store in my app. persist.tsimport { persistence, StorageAdapter } from 'mobx-persist-store'
import { CounterStore } from '@/store/index'
const read = (name: string): Promise<string> =>
new Promise((resolve) => {
const data = localStorage.getItem(name) || '{}'
resolve(data)
})
const write = (name: string, content: string): Promise<Error | undefined> =>
new Promise((resolve) => {
localStorage.setItem(name, JSON.stringify(content))
resolve(undefined)
})
export const PersistState = persistence({
name: 'CounterStore',
properties: ['counter', 'increment', 'decrement'],
adapter: new StorageAdapter({ read, write }),
reactionOptions: {
// optional
delay: 2000,
},
})(new CounterStore()) And I changed my code to use context.tsimport React from 'react'
import { stores, PersistState, CounterStore } from '@/store/index'
import type { ICounterStore } from '@/types/index'
export const FrameItContext = React.createContext<ICounterStore>(PersistState)
export const useCounterStore = () => React.useContext(FrameItContext) How do I solve it? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 16 replies
-
You should elaborate on "it stopped working". |
Beta Was this translation helpful? Give feedback.
-
Or just write it by hand: create a computed property that gives back the
things that you want to serialize. In general I don't think libraries for
this are in many cases not needed :)
…On Wed, Feb 24, 2021 at 8:09 AM Daniel K. ***@***.***> wrote:
If you want to save yourself some pain, you can consider mobx-state-tree
or mobx-keystone which offer persistence out-of-box. I don't have any
experience persisting pure mobx, so good luck I guess :)
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#2798 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAN4NBCJMY4BRJRNXL3I7P3TASX5JANCNFSM4XQQITPA>
.
|
Beta Was this translation helpful? Give feedback.
-
Or to simplify it a bit: lodash.pick might get you pretty far
On Wed, Feb 24, 2021 at 8:33 AM Michel Weststrate <[email protected]>
wrote:
… Or just write it by hand: create a computed property that gives back the
things that you want to serialize. In general I don't think libraries for
this are in many cases not needed :)
On Wed, Feb 24, 2021 at 8:09 AM Daniel K. ***@***.***>
wrote:
> If you want to save yourself some pain, you can consider mobx-state-tree
> or mobx-keystone which offer persistence out-of-box. I don't have any
> experience persisting pure mobx, so good luck I guess :)
>
> —
> You are receiving this because you are subscribed to this thread.
> Reply to this email directly, view it on GitHub
> <#2798 (reply in thread)>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AAN4NBCJMY4BRJRNXL3I7P3TASX5JANCNFSM4XQQITPA>
> .
>
|
Beta Was this translation helpful? Give feedback.
-
This is the code that works. Here's the Codesandbox → https://codesandbox.io/s/mobx-persist-store-manual-implementation-vm38r?file=/src/store.ts import { observable, action, makeObservable, computed, autorun } from "mobx"
import pick from "lodash.pick"
type Color = "red" | "blue" | "green"
export interface ICounterStore {
counter: number
color: Color
switchColor(color: Color): void
increment(n: number): void
decrement(n: number): void
}
export class CounterStore implements ICounterStore {
// private state = ""
counter = 0
color: Color = "red"
constructor() {
makeObservable(this, {
counter: observable,
color: observable,
increment: action.bound,
decrement: action.bound,
switchColor: action.bound,
})
const name = "CounterStore"
const storedJson = localStorage.getItem(name)
if (storedJson) Object.assign(this, JSON.parse(storedJson))
autorun(() => {
localStorage.setItem(name, JSON.stringify(this))
// const properties = ["counter", "color"]
// const storedJson = localStorage.getItem(name)
// console.log(storedJson)
// if (storedJson) {
// this.state = JSON.parse(storedJson)
// }
// // const value = toJS(_this)
// localStorage.setItem(name, JSON.stringify(pick(this, properties)))
})
}
increment(n: number) {
this.counter = this.counter + n
}
decrement(n: number) {
this.counter = this.counter - n
}
switchColor(color: Color) {
if (color === "red") this.color = "blue"
else if (color === "blue") this.color = "green"
else this.color = "red"
}
toJSON() {
return {
color: this.color,
counter: this.counter,
}
}
}
export const store = new CounterStore() Thank you @mweststrate @urugator |
Beta Was this translation helpful? Give feedback.
This is the code that works.
toJSON
contains the properties that need to be saved. Let me know if anything can be improved :)Here's the Codesandbox → https://codesandbox.io/s/mobx-persist-store-manual-implementation-vm38r?file=/src/store.ts