Skykid Felix
Skykid Felix

Reputation: 194

How do i maintain data throughout my SPA even when page reloads

I have a small-medium scale shopping website and I need to have a single storehouse for all my products without passing it through props. What am trying to do is fetch all my products and categories all at once.

So on my App.vue which is the parent component, I dispatch an action to call an API and populate the store with product data so I can use it throughout my website.

It works just fine when I navigate to other components on Vue router. But when I refresh the browser or revisit the same pages from the web, my product data goes away.

Since I no longer have to make requests to get the products data on each route, I just call the getters but now I can't maintain the store on page reload

Upvotes: 3

Views: 558

Answers (2)

wwerner
wwerner

Reputation: 4327

vuex-persistedstate transparently persists a vuex store (or parts of it) to local storage or cookies. I've been using it without bigger issues in a variety of smaller projects. Not sure how it will scale if you put in larger quantities of data, though.

To get started, simply install it into your project and register it as plugin when creating your store. The defaults will save the complete store to local storage.

import createPersistedState from "vuex-persistedstate";

//...

const store = new Vuex.Store({
// ...
  plugins: [createPersistedState()]
});

Upvotes: 2

Sombriks
Sombriks

Reputation: 3622

You can either save your state on localStorage or convert the SPA into a full-featured PWA with offline-ready content.

Either way would be wise to not store entire product catalog on client, but save a few short-lived most visited chunks of it.

Upvotes: 1

Related Questions