Search code examples
javascriptreactjsdvajs

DvaJS - Load saved state from localStorage into state


I initiate my dvajs app like below. Where I store state into localStorage with onStateChange hook. Saving states into localstorage works just fine.

const app = dva({
    history: createBrowserHistory(),
    defaultState: getPersistedState(),
    onError(e) {
        message.error(e.message, /* duration */3);
    },
    onStateChange(state){
        window.localStorage.setItem('adligence', JSON.stringify(state));
        console.log('state changed', state);
    }
});

Now when the page refreshes I want to load saved state into the app. so I wrote getPersistedState() and loading persisted state into defaultState. Which loads fine at initial load.

But the problem is when models setup states props are replaced by the models' default data. For example here is one of my model definition.

export default {

    namespace: 'training',

    state: {
        videos: [],
        current: {}
    }, ....
    ....

All loaded initial persisted data will be replaced by this model. So, how do I load the localstorage value into the state correctly so it stays?


Solution

  • Use initialState instead of defaultState on dva options. And for models set state to null and if you want to add any default props use initialState as well.

    Modified Code

    Dva Init

    const app = dva({
        history: createBrowserHistory(),
        initialState: getPersistedState(),
        onError(e) {
            message.error(e.message, /* duration */3);
        },
        onStateChange(state){
            window.localStorage.setItem('adligence', JSON.stringify(state));
            console.log('state changed', state);
        }
    });
    

    Model

    export default {
    
        namespace: 'training',
    
        initialState: {
            videos: [],
            current: {}
        },
        state: null
         ....
        ....