'mobx-persist returns the initial value for the first load
mobx-persist returns the initial value for the first time, after which it updates the storage from the local storage, so the first time we get not the last value, but the initial. How can i take last value in the first load
import { create } from 'mobx-persist';
import { enableStaticRendering } from 'mobx-react-lite';
// stores
import AppSettingStore from '@/store/stores/AppSettingStore';
enableStaticRendering(typeof window === 'undefined');
const hydrate = create({});
export default class AppStore {
appSettingStore = new AppSettingStore();
constructor() {
if (typeof window !== 'undefined') {
hydrate(`loginStore`, this.appSettingStore);
}
}
}
import { observer } from 'mobx-react-lite';
import useStore from '@/hooks/useStore';
import { useEffect } from 'react';
const Index = () => {
const {
appSettingStore: { cookie },
} = useStore();
useEffect(() => {
console.log(cookie) // return first time true(initial value), after sec false, because cookie is already was false
}, [cookie]);
};
export default observer(Index);
import { action, makeAutoObservable, observable } from 'mobx';
import { persist } from 'mobx-persist';
export default class AppSettingStore {
@persist @observable cookie: boolean = true;
constructor() {
makeAutoObservable(this);
}
@action
setCookie = (isOpen: boolean) => {
this.cookie = isOpen;
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
