Leveraging Vuex stores in a modular WebPack setup

I am currently working on a web application where each page of the site has 2 JS files: a global "bootstrap.js" file that is consistent across every page and a custom JS file specific to each page. I've run into an issue where I want these files to share a Vuex store, but changes made in one page do not reflect on the other. Does anyone have a solution for sharing a Vuex store across multiple pages?

One example I'm facing involves a shopping cart feature I'm developing. I would like the "bootstrap.js" file to utilize a Vuex store for the cart so that it can display the number of items in the cart on every page. Additionally, on certain individual pages such as the product description page, I want to use the same Vuex cart store to modify the cart contents and have those changes reflected in the "bootstrap.js" file. Here's a snippet of the code:

global_store.jsx:

import Vue from 'vue'
import Vuex from 'vuex'
import { doAsync } from '../utils/ajax'

Vue.use(Vuex)

const GET_CART_ASYNC = {
  SUCCESS: 'GET_CART_ASYNC_SUCCESS',
  FAILURE: 'GET_CART_ASYNC_FAILURE',
  PENDING: 'GET_CART_ASYNC_PENDING',
}

export let cartStore = new Vuex.Store({
  state: {
    cart: undefined,
    loading: false
  },
  mutations: {
    [GET_CART_ASYNC.SUCCESS](state, data) {
      Vue.set(state, 'loading', false)
      Vue.set(state, 'cart', data)
    },
    [GET_CART_ASYNC.FAILURE](state) {
      Vue.set(state, 'loading', false)
      Vue.set(state, 'cart', null)
    },
    [GET_CART_ASYNC.PENDING](state) {
      Vue.set(state, 'loading', true)
      Vue.set(state, 'cart', null)
    }
  },
  actions: {
    manipulateCart(store, action=null) {
      doAsync(store, `/cart/api`, GET_CART_ASYNC, action)
    } 
  }
})

boostrap.jsx:

import Vue from 'vue'
import { mapState } from 'vuex'
import { cartStore } from '../cart/global_store'

cartStoreGlobal.dispatch('manipulateCart')

new Vue({
  el: '#cart_display',
  store: cartStore,
  computed: mapState(['cart']),
  render(h) {
    if(this.cart === null) {
      return
    }
    var num_items = this.cart.map(cart_item => cart_item.quantity).reduce((accumulator, quantity) => accumulator + quantity, 0)
    return (
      <p class="navbar-text pull-right" id="mini-cart">
        <a class="button right" href="/cart">
          <strong>{num_items} items</strong> <span>$0.00</span>
        </a>
      </p>
    )
  }
})

cart.jsx

import Vue from 'vue'
import { mapState } from 'vuex'
import { CartView } from '../cart/cart_view'
import { cartStore } from '../cart/global_store'

// TODO: remove this as its already called in bootstrap.jsx, figure out how to use store singletons with webpack
cartStore.dispatch('manipulateCart')

new Vue({
  el: '#cart',
  store: cartStore,
  computed: mapState(['cart']),
  render(h) {
    return (<CartView 
      cart={this.cart} 
      remove_cb={(photo_id_to_remove) => cartStore.dispatch('manipulateCart', [{action: 'set', photo_id: photo_id_to_remove, quantity: 0}])}
    ></CartView>)
  },
})

The global_store contains the store definition and both boostrap and cart components are importing it. The specifics of the "doAsync" function are not critical. I'm still learning about Vue and Vuex, and may not fully grasp how WebPack functions, so any guidance or assistance in making this setup work seamlessly would be greatly appreciated!

Answer №1

Documenting this for future reference. The problem stemmed from the fact that the store was divided into separate files, creating two independent instances that did not communicate with each other. This explains why updating the state in one file had no impact on the other. Mystery solved.

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

Modify my JavaScript array by separating each element with a comma

JavaScript or jQuery is what I'm comfortable using Including an additional database table column has resulted in: 122461,4876192 Now there are 2 records So it displays like this: https://i.sstatic.net/7mjFY.png $.each(alldata.Data, function (in ...

Is it possible to alter the canvas origin when using an Orthographic camera with a CSS3D

When transitioning the camera from perspective to orthographic, I noticed that the camera's position also shifts so that the coordinates 0,0,0 are situated in the top left corner. Is this expected behavior? Check out this Example for reference. Ortho ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

Messages are not being received despite no errors occurring in the PHP form

I am facing a challenge with a PHP script that is supposed to send a form, but it keeps saying the email has been sent while nothing actually shows up. Do you have any insights on what might be causing this issue? Also, there's nothing in the spam fol ...

transmit JSON data with an AJAX request and receive a response

I'm looking to make a JSON request to an API and receive a response. I tested it using Postman and successfully received the following response: JSON request to API: { "apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp" } The response I receiv ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

Utilizing 'document.execCommand' for handling 'delete' key events in AngularJS

Here is a demo plunkr link that I have created to demonstrate the issue. I am looking to implement the strikeThrough command whenever there is a delete operation. For instance: If the user selects "Text" and presses the delete or backspace key, it should ...

Having trouble accessing a parsed JSON value in Node.js, encountering 1 error

Currently, I am working on creating a simple news web application as a way to practice utilizing APIs. The particular API that I have chosen for this project is . If you take a look at this JSON object that I am attempting to console.log, you will see the ...

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

What is the process for setting up both an open and closed status for my accordion?

After browsing through multiple threads on accordions, none seem to match my current structure which I believed was effective. In an attempt to learn and build elements from scratch, I created the following accordion with some help from Google and experi ...

Transmitting HTTP headers using Node.js

Within my Node JS Express application, I have an API endpoint called 'download' that returns a buffer to the calling application along with a header named 'status', which is a Javascript object. The response from Node sends the buffer ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

Javascript continues to conceal my web background without my permission

After loading my webpage, I click on a link and the expected javascript runs as planned. However, once it completes and presents the results, the page goes blank to a white screen displaying only the outcomes. My goal is to have these results showcased o ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

Can we move the "user" object to the forefront and retrieve it from a location other than the "on.AuthSateChanged(user => .... }" function?

Is there a way to define a ref in vuefire to firebase path that relies on the current User object? Can I bring the "user" object to the top level so it can be accessed outside the "on.AuthSateChanged(user => .... }" block? firebase-config.js import * ...