volna
volna

Reputation: 2610

Good practice for modifing vuex on initial app load

Introduction:
Currently the application has multiple modules that store data, for example:

- profile
- models
- products
- etc

... later components under the different routes reuse and modify store data.

The problem:
When the application is initially loaded (no matter what route, or component) it's needed that certain logic has to be executed in order to set the needed state of store.

Simple example can be:
Depending on the user's age in the profile:
1. Find a certain model in models
2. And update profile data with the values from model

There are methods like created() or mounted() during component creation, so it made me think about some sort of representational container under the parent route. But I wonder maybe there are different sort of hooks to be added on the initial application load.

Upvotes: 0

Views: 135

Answers (2)

Radu Diță
Radu Diță

Reputation: 14201

You usually feed your initial data into the store from another (persistent) data storage. This can be LocalStorage or an external source (an REST API for instance).

One way of doing this is too postpone app creation until the store is populated and then proceed with app init.

You init code in main.js will look something similar to this

import store from './store'

someAsyncTask()
.then( () => {
 new Vue({
   el: '#app',
   router,
   store,
   template: '<App/>',
   components: { App }
 })
})

This means that the user needs to wait until everything is loaded so presenting a static preloader (usually added in index.html) is a good option.

Upvotes: 3

volna
volna

Reputation: 2610

The solution for my problem ended up very obvious, but initially escaped my mind. Since the App (root component) is being passed to the Vue instance, all logic required for manipulating can be actually executed there during created or mounted methods.

However if you actually rely on the AJAX calls to be resolved before initialising the app the Radu Dita approach should be taken into the consideration.

Upvotes: 0

Related Questions