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

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Can a Stylus and Node.js with Express project utilize a local image?

Let's talk about using images in a Web app. In my Stylus file, style.styl, I typically set the image using code like this: .background background: url(http://path/to/image) But what if we want to save the image to our local app directory and use ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

Vuetify - What is the best way to include a 'Select' component inside a Header or text container?

As a backend developer diving into front-end work, please bear with me as I explore new territory. Picture a prominent header at the top of a web page: Displayed below is a list of available stock for ↓users-dropdown↓ By clicking on the ↓users-dro ...

Having difficulty choosing an item from a personalized autocomplete search bar in my Vue.js/Vuetify.js project

NOTE: I have opted not to use v-autocomplete or v-combobox due to their limitations in meeting my specific requirements. I'm facing difficulties while setting up an autocomplete search bar. The search functionality works perfectly except for one mino ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Input boxes next to each other in a Vuetify form

Is it possible to place multiple input controls next to each other using v-form? Thanks This is my code, I want to have the text edits side by side (2 on each line) <v-form ref="form" v-model="valid"> <v-select :items ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

Using NodeJS Script in conjunction with Express and setInterval

Feeling stuck and unable to find clear answers for the best solution. I have a Node.js app that serves APIs with MongoDB as the database. I created a setInterval within the request to update the data every 30 seconds. This was done to prevent the Node.js ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

"An error message is displayed stating that the maximum call stack size has been exceeded while looping through an

Dealing with an array containing 10,000 items and attempting to assign a new property to each item has been a challenge for me. _async.mapLimit(collection, 100, function (row, cb){ row.type = "model"; cb(null, row); }, function (err, collect ...

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Encountering a TypeError stating that searchField.toLowerCase is not a function while employing hooks and redux in the

I've been working on a project to dive deeper into react. Recently, I made the switch to using hooks and attempted to integrate redux into it. However, I encountered an error that says: TypeError: searchField.toLowerCase is not a function After consu ...

Is it possible to create a multi-page single-page application using Vue js SSR?

It may appear contradictory, but I struggle to find a better way to express it. When using vue server-side rendering, it seems you are limited to single page applications. However, for various reasons, I require an application with multiple real server-s ...

Using an `<img>` element as an event handler in a JavaScript function

I'm having trouble setting up a click handler for the search field in my project. I've tried using on() with an img or class, but it's not working as expected. When adding the image using the code below: jQ('#psc').append('&l ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

What is the proper way to send properties to a component that is enclosed within a Higher Order Component?

I have a situation where I need to pass props from the index page to a component wrapped inside two higher-order components. Despite fetching the data successfully in getStaticProps, when passing the props to the About component and console logging them in ...