What is the proper location to place state initialization code within Vuex?

Should a Vuex store only contain the code for the state structure and how to modify that state (mutations, actions), or should it also include the actual state initialization and values?

I began contemplating this question when my state initialization code started becoming more complex, as I couldn't find a natural place within the Vuex architecture to integrate this code.

Consider the following store:

export default {
  state: {
    list: []
  },

  mutations: {
    addItem(state, { item }) {
      state.list.push(item);
    }
  }
}

If the list starts off empty, it works fine. But what if I have default values for the list and I want to store the list in LocalStorage to preserve its value between page loads?

const STORAGE_LIST_KEY = 'list';

const LIST_DEFAULT = [
  {
    id: 1,
    name: 'item 1'
  },
  {
    id: 33,
    name: 'item 33'
  }
];

function initializeList() {
  let savedList = localStorage.getItem(STORAGE_LIST_KEY);
  return savedList ? savedList : LIST_DEFAULT;
];

Is there a specific location in the Vuex store architecture where the initializeList() function should be placed? (For example, in a Vue component, I would typically place initializeList() within the methods section of the component). Or is it possible that the store is solely responsible for the structure, while the initialization code should belong to the Vue components?

Answer №1

When initializing your state, consider implementing a mutation or action that caters to async and side effects requirements. This particular action should only be executed once during the initialization process.

To execute this mutation/action, it can be triggered from the root instance or a component at a higher level. Alternatively, breaking down the initialization of the application state into smaller mutations or actions is also an effective approach.

An added benefit of this method is the ability to divide your Vuex store and load Vuex modules dynamically through lazy loading.

In scenarios where you need to manage inflating/deflating state from local storage (a side effect), utilizing an action makes practical sense.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Tips for extracting value from PHP and transferring it to a jQuery function

I am trying to calculate the distance between two airports and pass this value back to a jQuery function to use it in further calculations. I'm unsure of where I went wrong? HTML: The 'dept' and 'dest' inputs fetch airport informa ...

What is the process for configuring aliases in vuepress or vuejs using configureWebpack?

In my config.js file, I have set the configureWebpack parameter like this: configureWebpack: { resolve: { alias: { 'alias': '/easym/imgs/' } } }, Here is my folder structure: -/easym --/.vuepress -- ...

Refresh the Rails HTML table with new data by incorporating ajax requests and vanilla JavaScript

I'm struggling to find a solution without using jQuery in my current scenario. How can I refresh a partial on my page without reloading the entire page? Within my new.html.erb file, there's a button that triggers a JavaScript function each time ...

The Access-Control-Allow-Headers Error prohibits the use of the Authorization request header field

I am currently working on integrating a VueJS frontend application with an ExpressJS backend server. In my server code, I have implemented the following: var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin&ap ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

How to access variables with dynamic names in Vue.js

I'm curious if it's possible to dynamically access variables from Vue’s data collection by specifying the variable name through another variable. For instance, consider the following example: Here are some of the variables/properties: var sit ...

Creating an intranet website that can access a database dynamically without the need for a server or server side scripts is a

I have encountered a challenge where I need to create an Intranet webpage without the server for hosting. I have been attempting to update an Access database using HTML and javascript, but unfortunately, it is not working with the code below. Any assistanc ...

What is the best way to combine two objects by summing up the numerical values of matching keys?

I am currently working with 2 objects and using the jQuery extend function. However, I am facing an issue where values from keys with the same name are being overridden. How can I combine or add these values together instead? var obj1 = { "orange": 2, ...

Utilizing jQuery boilerplate to execute functions

I am currently utilizing jQuery Boilerplate from However, I have encountered an issue where I am unable to call the "openOverlay" function within the "clickEvents" function. Oddly enough, I am able to successfully call "openOverlay" within the "init" fun ...

Creating intricate HTML components using jQuery/Javascript

My current challenge involves receiving data from JSON and dynamically displaying it on a web page within complex HTML structures, such as tables with lists. Every time new JSON data is received, I need my HTML elements to be dynamically regenerated. For ...

Basic $http.get request including parameters

I've been attempting to send an HTTP request using the AngularJS $http service like this: $http.get('http://myserver:8080/login?', { params: {username: "John", password: "Doe" }, headers: {'Authorization': ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

Recursive method used to create an object by looping through an array

I'm really struggling with this algorithm. It needs to be recursive, but I can't seem to crack it. Any help would be greatly appreciated. Thank you! Here is the problem: ['a','b','c',['d','e',&ap ...

The Disable Button is malfunctioning as the text is deleted but the button remains enabled

One issue I am facing is that even after removing the numbers from the textboxes, the submit button remains enabled. Initially, when I enter inputs in the textbox, it enables the button, but even after removing a number, the button stays enabled. This is ...

Update the navigation logo while scrolling

My website has a scrolling navigation menu using Wordpress. The default logo color is green, but when the user scrolls, a white background appears. However, on specific screens, I need the initial logo to be white. I have managed to create an alternate na ...

Combine elements of an array of objects to create a coherent sentence

Received an API response structured as follows: "payload": { "paragraph": { "id": 2692, "words": [ { "id": 21679, "position": 2, ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

What is the best way to integrate Angular 5 with various sources of JavaScript code?

I am fairly new to angular. I am looking to merge an external angular script file and on-page javascript code with angular 5. I understand that angular does not typically allow for the inclusion of javascript code in html components, but I believe there m ...