Simple Vuex plugin to keep data across pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const persistInterval = 24*60*60*1000; // 1 day | |
const plugin = store => { | |
store.subscribe( ( mutation, state ) => { | |
// Save to local storage all the changes made in the cart state | |
if( 'shop/addToCart' === mutation.type || 'shop/removeFromCart' === mutation.type ) { | |
let record = { data: state.shop.cart, ts: new Date().getTime() + persistInterval }; | |
try { | |
localStorage.setItem( 'my_site_cart', JSON.stringify( record ) ); | |
} catch(e) {} | |
} | |
// When cart is created, get the state from local storage if exists | |
if( 'shop/initStore' === mutation.type ) { | |
let storage = false; | |
try { | |
storage = localStorage.getItem( 'my_site_cart' ) || false; | |
if( storage ) { | |
storage = JSON.parse( storage ); | |
} | |
} catch(e) {} | |
if( storage && new Date().getTime() < storage.ts ) { | |
store.commit( 'shop/setCart', storage.data ); | |
} | |
} | |
}); | |
} | |
export default plugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment