Changes to the Vuex state are made using a specific function to mutate it, not a general function

I am utilizing a storage provided by LokiJS to update the Vuex state through mutations in the autoloadCallback.

The LokiJS storage setup:

var db = new loki('mydatabase', {
  autoupdate: true,
  autoload: true,
  autoloadCallback: setupHandler
})

Managing Vuex state and mutations:

const state = {
  ads: []
}

const mutations = {
  updateArray(from, to) {
      from = to
  },
  updateAds() {
      state.ads = db.getCollection('ads').data
  }
}

Exploring the callback function:

function setupHandler() {
  setupCollection('ads') // Creates the collection if it doesn't exist
  db.getCollection('ads').insert({dummy: "Dummmy!"})

  mutations.updateArray(state.ads, db.getCollection('ads').data) 
  mutations.updateAds()    
}

The problem arises when calling updateArray(state.ads, content) as it does not update state.ads to content. On the other hand, updateAds() function achieves the same outcome by dynamically updating state.ads. What is the root issue with attempting to create a generic function like updateArray? Is there a work-around?


For a demonstration, check out this JSFiddle MCVE example showcasing this behavior.

Answer №1

It's important to consider the details of your loki before making any changes.

To ensure proper functionality, your mutation should be structured as follows:

const mutations = {
  updateArray(state, newData) {
      state.content = newData
    }
}

Additionally, your setupHandler function should be defined as such:

function setupHandler() {
  setupCollection('content')
  db.getCollection('content').insert({example: "Example data"})

  store.dispatch('updateArray', db.getCollection('content').data)
}

Mutations in Vuex are functions that take the state as the first parameter and an object containing data as the second parameter. Remember to commit mutations using the store's dispatch method.

Feel free to view the updated JSFiddle demo.

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

When a web page is translated using Google Translate, Vue components may cease to update properly

When Vue components on pages are translated using Chrome's translate feature, the components stop re-rendering and updating the view. For example, if you try to translate https://v2.vuejs.org/v2/guide/#Handling-User-Input in Chrome to a different lan ...

Tips for initiating and terminating the evaluation of a condition at regular intervals using JavaScript

I'm currently working on a JavaScript application where I need to achieve the following: Periodically check every 5 seconds to see if there is an element with the 'video' tag on the page. Once an element with the 'video' tag ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

The ::before pseudo element is malfunctioning when used in the makeStyles function

I am currently utilizing the makeStyles function in React, but I seem to be facing an issue where the content within the ::before pseudo-element is not displaying. Strangely enough, when the content is an image it works fine, but text does not render. Jus ...

The JavaScript function is unable to fetch information from the controller

I am working with a controller called Map1 that returns a JSON object. Within my scripts folder, there is a .js file named init.js. In this file, I am attempting to call the controller using the following code: $(document).ready(function() { $.getJSO ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

Discover how ReactJS can dynamically display or hide div elements based on specific conditions being met within JSON data

How do I show or hide a div based on a condition in React, using data from a JSON array? I have implemented the code below, but changing the value of isPassed={resultPass.pass} to isPassed={resultPass.failed} still displays the result as pass. I came acro ...

A Guide on How to Sort and Tally Items in a JSON Data Set containing Numerous Objects using JavaScript

I have recently started learning javascript, and everything was going well until I encountered this issue. I need to reformat a JSON file in the following structure: { firstName: "Joel", lastName: "Munz", total: 154, transaction: "111111", ...

Display a limited number of characters along with a button on the blog tag pages. Clicking on the button will reveal the complete text description

Hey, I am looking to replicate the way WooCommerce tags descriptions are displayed on my WordPress blog. I want it to show only a certain number of characters with a "show all" link, similar to how it appears on this site: I have found some code that work ...

Obtaining the file size on the client side using JSF RichFaces file upload

I am currently using version 4.3.2 of rich fileupload in JSF richfaces. The issue I am facing is that the files first get uploaded to the server and then an error is thrown if the file size exceeds a certain limit. Even though I have set a size restriction ...

Tips for eliminating corner indexes from a 2D array?

Exploring forward ray tracing algorithm using Three.js. I have developed a sample using a 2D array where the Spotlight's location is parsed, but not directly involved. To create lines of sight, I set: startPoint = position of SpotLight endPoint = ...

Place a check mark in the corner of the button

I am looking to add a checkmark on my button in the right corner. I have set the input value and it displays a button with a check mark, but I want it to be positioned in the right corner. .buttoner{ background-color: #4CAF50; b ...

What is the best way to simulate the "window.screen.orientation.lock" function with Jest?

Within our hybrid app, we have implemented a cordova plugin to control screen orientation. The AppComponent contains code that manages the screen orientation locking using the window.screen.orientation.lock function. Is there a way to create a mock versi ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Newbie's guide: Saving information in Ruby on Rails

In my Rails 4 application, I am looking to save questions and answers either in a document or database. Once stored, I want to showcase them on a specific webpage for users to respond. For instance, I envision having a page titled /questions where a quest ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Subclass declaration with an assignment - React.Component

I recently started going through a React tutorial on Egghead and came across an interesting class declaration in one of the lessons: class StopWatch extends React.Component { state = {lapse: 0, running: false} render() { const ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...