I have data between sessions that is saved in window.localStorage. When a new session starts a plugin will grab the data and add it to the store.
// ./store/data.js
export const state = () => ({
data: []
})
export const mutations = {
addItemToData (state, item) {
state.data = state.data.push(item)
},
setData (state, data) {
state.data = data
},
}
// ./store/index.js
import localStorage from '../plugins/localStorage'
export const plugins = [localStorage]
// plugins/localStorage.js
const localStorage = store => {
store.subscribe((mutation, state) => {
if (mutation.type === 'data/addItemToData') {
console.log('saving added item to storage')
window.localStorage.setItem('data', JSON.stringify(state.data.data))
}
})
// called when the store is initialized
if (typeof window !== 'undefined') {
if (window.localStorage.data) {
store.commit('data/setData', JSON.parse(window.localStorage.getItem('data')))
}
}
}
export default localStorage
I've thrown all sorts of console statements in, and they all seem to output what they should. The data is in the localStorage, the mutations are firing, but after all that the data isn't in the store.
Any help would be great, thanks!