Issue with electron-vue: Unable to modify Vuex state when using RxJS subscribe

I need help with my code involving two functions in the mutations and two pieces of state

const state = {
  files: [],
  uploadProgress: 0
}

const mutations = {

  SET_UPLOAD_IMAGE: (state, files) => {
    state.files = files
  },

  UPLOAD_IMAGE: (state) => {
    StandbyService.uploadImage(state.files).subscribe(progress => {
      state.uploadProgress += progress
      console.log(`Upload Progress ${progress}%`)
    })
  }

}

SET_UPLOAD_IMAGE function is used to update the files state, while UPLOAD_IMAGE triggers the image uploading process to the server. The issue I'm facing involves updating the uploadProgress state based on the progress received during the upload process using an Observable from uploadImage(). However, I keep encountering errors as shown in the image below:

https://i.stack.imgur.com/Zp90a.png

I've spent over 4 hours trying to resolve this error without success. Any help or suggestions would be greatly appreciated. Thank you.

Answer №1

In order to handle asynchronous tasks, it is recommended to use actions as specified in the documentation.

Actions serve a similar purpose to mutations but with key differences:

  1. Instead of directly changing the state, actions trigger mutations.
  2. Actions can include asynchronous operations.

It is crucial to note that mutations should not be used for async tasks, according to the provided guidelines.

An important guideline states that mutation handler functions must be synchronous.

Therefore, you can define an action to handle your progress updates accordingly

const state = {
  files: [],
  uploadProgress: 0
}
const action:{
  uploadImage({commit,state}, payload){
   StandbyService.uploadImage(state.files).subscribe(progress => {
      commit('updateProgress', progress)
      console.log(`Upload Progress ${progress}%`)
    })
  })
  }
}
const mutations = {

  SET_UPLOAD_IMAGE: (state, files) => {
    state.files = files
  },

  UPLOAD_IMAGE: (state) => {
    //this action is no longer necessary
  },

  UPDATE_PROGRESS: (state, progress){
    state.uploadProgress += progress
  },

}

I hope this explanation proves helpful.

Answer №2

In the world of Vue, modifying state without mutation is frowned upon.

The only legitimate way to make changes to state in a Vuex store is through committing a mutation.

This warning message is being triggered for that reason.

To resolve this issue, consider creating a mutation; instead of directly updating with state.uploadProgress += progress, use something like SET_UPLOAD_IMAGE.

Just follow these steps and everything should function correctly.

I trust this guidance will be beneficial to you.

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

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Is it possible for the upload form submission to wait until the file processing is finished?

Is it possible for the form submission to wait until the file processing is complete? I am currently using web2py and its sqlform to upload a video file. As the file is being uploaded, it is also being converted to flv format. The progress of both uploadi ...

Having trouble with Window.open on Mobile Devices and Canvas?

I've created a unique "button" within the div element. This button is designed to detect user interaction, such as clicks or taps, and when triggered, it should open a new window with the URL: "http://www.google.com". However, while this functionality ...

Computed properties are not being updated based on changes in the length of the Vuex state object

I'm attempting to retrieve the length of a state object from a computed property, but for some reason it is not reactive. Here is the structure of the state: state: { user: { cards: {}, } } This is the getter in my store: cardCount(sta ...

Spying on functions within Vue 3 setup() is not allowed

What is the best way to create a Jest test that triggers the function resetTimer and verifies that startTimer is also triggered? JS Code: setup () { const startTimer = () => { // ... }; const resetTimer = () => { startTi ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...

Accessing the Angular scope and making modifications using Chrome browser

I need to access the $scope value in order to update its data values via a chrome extension. I have attempted to obtain the $scope using the code below: var $scope = angular.element(document.getElementById('name')).scope() While this code wor ...

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

"Exploring the possibilities of RSelenium and Javascript together

While I have a strong understanding of R, my knowledge in javaScript and other languages is very limited. My goal is to access information from a publicly-available data set found here: . Specifically, I have a list of postal codes formatted as 'A1A1A ...

Transforming the breakpoint can cause fluctuations in the jQuery UI selectable selected event

I'm running into an issue with a jQuery UI selectable div that contains child divs. The problem is that the child divs are not getting selected until I insert a breakpoint inside the selected handler. For a live example, please see my JS Fiddle: htt ...

How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement: Math.random() > 0.5 ? 'spikes' : 'slime' I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those th ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...

Exploring Selenium: Clicking on Auto-Complete Suggestions using Python

Attempting to interact with an auto-complete search bar on the site in order to search for results. Wanting to click on the drop-down element that appears after entering a city name to perform a full city name search and obtain results. Below is the cod ...

Displaying the information from a nested array of objects in an HTML table through iteration

In the code snippet below, there is an input with a nested array of objects. The main array of objects is called summary and within it, there's a nested array called run_type. let input = { "summary": [ { " ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...