diff options
Diffstat (limited to 'src/lib/persisted_state.js')
| -rw-r--r-- | src/lib/persisted_state.js | 72 |
1 files changed, 47 insertions, 25 deletions
diff --git a/src/lib/persisted_state.js b/src/lib/persisted_state.js index 60811e65..ccd92633 100644 --- a/src/lib/persisted_state.js +++ b/src/lib/persisted_state.js @@ -1,7 +1,7 @@ import merge from 'lodash.merge' import objectPath from 'object-path' import localforage from 'localforage' -import { throttle, each } from 'lodash' +import { each } from 'lodash' let loaded = false @@ -12,18 +12,20 @@ const defaultReducer = (state, paths) => ( }, {}) ) +const saveImmedeatelyActions = [ + 'markNotificationsAsSeen', + 'clearCurrentUser', + 'setCurrentUser', + 'setHighlight', + 'setOption', + 'setClientData', + 'setToken' +] + const defaultStorage = (() => { return localforage })() -const defaultSetState = (key, state, storage) => { - if (!loaded) { - console.log('waiting for old state to be loaded...') - } else { - return storage.setItem(key, state) - } -} - export default function createPersistedState ({ key = 'vuex-lz', paths = [], @@ -31,13 +33,20 @@ export default function createPersistedState ({ let value = storage.getItem(key) return value }, - setState = throttle(defaultSetState, 60000), + setState = (key, state, storage) => { + if (!loaded) { + console.log('waiting for old state to be loaded...') + return Promise.resolve() + } else { + return storage.setItem(key, state) + } + }, reducer = defaultReducer, storage = defaultStorage, subscriber = store => handler => store.subscribe(handler) } = {}) { - return store => { - getState(key, storage).then((savedState) => { + return getState(key, storage).then((savedState) => { + return store => { try { if (typeof savedState === 'object') { // build user cache @@ -60,23 +69,36 @@ export default function createPersistedState ({ value: store.state.config.customTheme }) } - if (store.state.users.lastLoginName) { - store.dispatch('loginUser', {username: store.state.users.lastLoginName, password: 'xxx'}) + if (store.state.oauth.token) { + store.dispatch('loginUser', store.state.oauth.token) } loaded = true } catch (e) { console.log("Couldn't load state") + console.error(e) loaded = true } - }) - - subscriber(store)((mutation, state) => { - try { - setState(key, reducer(state, paths), storage) - } catch (e) { - console.log("Couldn't persist state:") - console.log(e) - } - }) - } + subscriber(store)((mutation, state) => { + try { + if (saveImmedeatelyActions.includes(mutation.type)) { + setState(key, reducer(state, paths), storage) + .then(success => { + if (typeof success !== 'undefined') { + if (mutation.type === 'setOption') { + store.dispatch('settingsSaved', { success }) + } + } + }, error => { + if (mutation.type === 'setOption') { + store.dispatch('settingsSaved', { error }) + } + }) + } + } catch (e) { + console.log("Couldn't persist state:") + console.log(e) + } + }) + } + }) } |
