Skip to content

Instantly share code, notes, and snippets.

@luistinygod
Last active February 2, 2020 09:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luistinygod/fc744d3a1e72555d1746ebd61a490b93 to your computer and use it in GitHub Desktop.
Save luistinygod/fc744d3a1e72555d1746ebd61a490b93 to your computer and use it in GitHub Desktop.
Simple Vuex plugin to keep data across pages
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