Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to initialize the vuex store when app is starting [closed]

I have a doubt about this topic, i would need to initilize the vuex store at the very beginning.

In details, I would need to retrive some data from Local Storage to the Vuex store because these data will decide which landing page the user will land on.

My questions are:

  1. Where is the best place (best practice) to do this in a vue project?

  2. Is there a vantage doing this (copy data from local storage to vuex store) ? is not the same if i read directly the local storage data without use vuex, with localStorage.getItem('key')?

Thank you

like image 207
Trispo Avatar asked Oct 18 '25 12:10

Trispo


1 Answers

1- Where is the best place (best practice) to do this in a vue project?

If you want to set the data of the local storage to your vuex store by generate ( whatever the page you are in ), it would be better to create a plugin to do that.

If storage will depend on the page or component you are in, you can use beforeCreated lifecycle.

2- Is there a vantage doing this (copy data from local storage to vuex store) ? is not the same if i read directly the local storage data without use vuex, with localStorage.getItem('key')?

As @RobinRider mentioned on Quora

Well, Vuex and LocalStorage do different things and are not mutually exclusive. Vuex is typically used to maintain the state while the application is in use. LocalStorage is often used for persisting state between application runs. Example: refreshing the browser window will wipe the Vuex state, but everything in LocalStorage remains unchanged. Having said that, Vuex is much more advanced when it comes to handling state data. LocalStorage is essentially just a list of JSON-encoded data. You can retrieve that data, and set it. Nothing more. Below are a couple benefits of using Vuex.

Code Duplication By using a state management library, such as Vuex, you can avoid duplicating code if you need to access state data in multiple parts of your application. You only need to create methods for reading and parsing state data once in a Vuex store. Every time you want to load something from LocalStorage, you will need to also make sure to decode the result per your needs. Depending on your application, that may or may not be simple.

Getters You are able to provide custom functions used to provide derived versions of the application state. The results of these functions are cached, only being updated when the data they depend on is updated. This provides uniform results across your application. Getters | Vuex

Actions You can provide functions to perform certain tasks, and then update the state after these tasks are completed. One of the biggest benefits of actions is that they are asyncronous, making it easy to use AJAX to query a server, and then commit that data to the application state.

like image 193
Mina Avatar answered Oct 21 '25 22:10

Mina