How to save Mobx state in sessionStorage

后端 未结 4 661
无人共我
无人共我 2021-02-13 21:54

Trying to essentially accomplish this https://github.com/elgerlambert/redux-localstorage which is for Redux but do it for Mobx. And preferably would like to use sessionStorage.

4条回答
  •  爱一瞬间的悲伤
    2021-02-13 22:04

    Turns out you can do this in just a few lines of code:

    const store = observable({
        players: [
            "Player 1",
            "Player 2",
        ],
        // ...
    })
    
    reaction(() => JSON.stringify(store), json => {
        localStorage.setItem('store',json);
    }, {
        delay: 500,
    });
    
    let json = localStorage.getItem('store');
    if(json) {
        Object.assign(store, JSON.parse(json));
    }
    

    Boom. No state lost when I refresh the page. Saves every 500ms if there was a change.

提交回复
热议问题