The e-commerce site now works great! We can add a product, list the products, open the product details page, and also add a product to the shopping cart.

But when we reload the page, all the data goes away!

This is because we don’t have any way of persisting the data. It’s all volatile.

There are various ways to persist data. The simplest one is to use the Web Storage API provided by browsers and use either localStorage or sessionStorage (there are differences in how they work).

There is a cool Vuex plugin called vuex-persist which is a great help. Install it using npm/yarn:

npm install --save vuex-persist
# or
yarn add vuex-persist

or add it to CodeSandbox in the usual way.

Once installed you import it into the store (in the src/store.js file), and you initialize it:

import VuexPersist from 'vuex-persist'

const vuexLocalStorage = new VuexPersist({
  key: 'ecommerce', // a unique key to store the data
  storage: window.localStorage
})

The only thing we must do now is to add

plugins: [vuexLocalStorage.plugin]

to the store configuration, and now every single change to the Vuex store will be synced to the local storage.

That’s it! Now the cart works fine, and if we reload the page, the data persists!

The current code is available at https://codesandbox.io/s/p90kv9oy2j


Go to the next module