Ways to maintain an array in Vuex even after mutations take place? (Specifically focusing on persisting data through browser refresh)

I am in the process of developing a basic shopping cart and I need guidance on how to persist an array containing cart data when executing the addProduct mutation below. Is there a way to save this data temporarily to prevent it from being lost due to browser refreshing? I have heard about vuex-persistedstate, but how can I implement it in this particular scenario?

import Vue from 'vue';
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
Vue.use(Vuex);

export const store = new Vuex.Store({

plugins: [
createPersistedState({
  getState: state.cartdata;
  setState: state.cartdata;
})
]

state: {
 cartdata: []
},

mutations: {
 deleteProduct: function(state, product){
  state.cartdata.splice(state.cartdata.indexOf(product), 1);
 },

addProduct: function(product){
      this.$store.state.cartdata.push({
        id: product.id,
        name: product.name,
        price: product.price,
        quant: 1
      })
}


},

Answer №1

In a nuxtjs project or basic JavaScript setup where the window object is defined, you can utilize nuxt-storage for data storage.

    import Vue from 'vue';
    import Vuex from 'vuex'
    import nuxtStorage from 'nuxt-storage';
    Vue.use(Vuex);

    // Without Nuxt-Storage
    let cartdata = window.localStorage.getItem('cartdata');

    // With Nuxt-Storage
    let cartdata = nuxtStorage.localStorage.getData('cartdata');


    export const store = new Vuex.Store({

    state: {
     // Check if information is stored in local storage, if not set array to empty
     cartdata: cartdata ? JSON.parse(cartdata) : [],
     // cartdata: []
    },

    mutations: {
     // Using destructuring to add state and commit

     deleteProduct: function({commit, state}, product){
      state.cartdata.splice(state.cartdata.indexOf(product), 1);
      commit('saveCart');
     },


    addProduct: function({commit}, product){
          this.$store.state.cartdata.push({
            id: product.id,
            name: product.name,
            price: product.price,
            quant: 1
          })
     commit('saveCart');
    },

    saveCart(state) {
        // With Nuxt-Storage
        nuxtStorage.localStorage.setData('cartdata', JSON.stringify(state.cartdata));

        // Without Nuxt-Storage
        window.localStorage.setItem('cartdata', JSON.stringify(state.cartdata));

      }


    },

Note: When working with nuxt, remember that the structure for exporting mutations, actions, getters, and state may differ and should be considered.

If commit('saveCart'); is not functioning, try using this.commit('saveCart'); Check out this blog post for an example of persisted cart implementation.

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

What is the best way to activate a click event in Vue.js?

Hey there! I'm facing a situation where I have a button within the child component that emits an event when clicked. Is there a way to trigger this event when the parent component is mounted? Alternatively, is there another method to achieve this goal ...

Various tasks to be executed on a shared element

Struggling with implementing actions on a grid component without using a router in Next.js. Here is the current code snippet: const handleActions = (btnPress, row) => { if (btnPress === "Add") {/* implementation */} else if (btnPr ...

Encountering difficulties when attempting to test Vue CSS styling

Encountering difficulties in my unit tests while attempting to test a method that alters the CSS style "display" to "none". The test fails with this message: Expected: "display: none" Received: undefined Within my component, there is a method: closeCook ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Retrieve the substring following a specific keyword within an array of strings

I am working with a txt file that I have read as an array, where each line in the txt file is stored as an element in the array. My objective is to extract only the array elements that start with the word "Keywords:". I need to retrieve all the words follo ...

Navigating using passing data in ReactJs

The following data contains information about people: const people = [ { img: 11, name: "Ahmed", job: "developer", }, { img: 13, name: "Kazim", job: "Engineer", }, ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

The external function in HTML Form's onsubmit attribute is failing to execute

My HTML Form has an onsubmit event that should call a validate() function. Everything works fine when the validate() function is inside a script tag at the end of the body tag. But if the validate() function is in an external JavaScript file, like in thi ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

I am currently studying react.js and struggling to comprehend how the deployment process for a react app functions

Will the server only serve the index.html file or is there a way for the client to run that html file as it's not a regular html file? Do I need a backend node to make it work? I'm having trouble understanding the entire process. Normally, a cli ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...

Getting a JSON array response with Java's HttpsURLConnection

Up until now, I have been using HttpsURLConnection to receive JSON objects as a response and then parsing them using the code below: ObjectMapper map = new ObjectMapper(); JsonNode node = map.readTree(conn.getInputStream()); Everything has been working s ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Ways to customize the TextInput component in React-Admin

I am facing a challenge with overriding specific fields in my custom theme. It seems that setting the custom theme also overrides other fields unintentionally. I attempted to use useStyles to resolve this issue, but unfortunately, it did not work as expec ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

Accessing `this.$refs`, `this.$router`, and `this.$route` using the Vue 2 Composition API

Is there a way to access this.$refs, this.$router, and this.$route in the setup function of Vue 2 Composition API? I've seen suggestions using context.$root, but it appears that $root is no longer accessible with context. Any guidance on this issue wo ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...