Originally, I was using new CounterStore
inside React.createContext()
context.ts
import 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.ts
import { 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) || '{}'
console.log('got data: ', data)
resolve(data)
})
const write = (name: string, content: string): Promise<Error | undefined> =>
new Promise((resolve) => {
localStorage.setItem(name, content)
console.log('write data: ', name, content)
resolve(undefined)
})
export const PersistState = persistence({
name: 'CounterStore',
properties: ['counter'],
adapter: new StorageAdapter({ read, write }),
reactionOptions: {
// optional
delay: 2000,
},
})(new CounterStore())
And I changed my code to use PersistState
instead of new CounterStore()
context.ts
import 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)
It only logs got data: {}
to the console. The write
function never gets called.
Is there anything I am doing wrong?
Coincidentally, a simple Counter example on Codesandbox works perfectly fine → https://codesandbox.io/s/mobx-persist-store-4l1dm