Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows:

try {
  const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: 'Bearer ###'
    }
  });

  var obj = cloneDeep(response.data);
  var temp = cloneDeep(response.data.line_items_attributes.nested_form)

  temp = Object.keys(temp).map(key => {
    return {
      ...temp[key]
    }
  });

  obj.line_items_attributes.nested_form = cloneDeep(temp);

  state.form = cloneDeep(obj);
  console.log(state.form);
} catch (error) {
  ...
}

The state should now contain an array with an object inside. Checking the state confirms this, and it is displayed in the view. However, upon reloading the page, everything remains in the state except for the object inside the array. It only shows an empty array in the store:

line_items_attributes:
  attribute: "line_items_attributes"
  label: "Positionen"
  model_class: "expense_line_item"
  nested_form: []              // <---- Object is missing

The nested_form is a hashmap provided by the backend, which I convert into an array. line_items_attribute is a property of the object stored in the state. EDIT: However, even without the transformation, the assigned state does not get preserved.

store.js

const store = createStore({
    strict: false,
    plugins: [createPersistedState()],
    modules: {
        expense,
        invoice
    }
});

Calling the action/mutation as follows:

const updateOuter = (event, refreshable, propertyName) => {
   store.dispatch('expense/updateOuterValue', ({
      refresh: refreshable,
      propertyName: propertyName,
      value: event.target.checked ? 1 : 0
   }))
};

EDIT:

After changing a different value following the mutation call, the nested_form object is retained after the reload.

It appears to work if I invoke the mutation twice... Any thoughts on why this might be happening?

Answer №1

The issue stemmed from the use of axios within the Vuex mutation. It is crucial to avoid any asynchronous operations inside a mutation, as advised by @e200

Avoid incorporating async tasks within mutations and opt for actions instead.

Therefore, adhering to this principle is not just a best practice but a necessary action. For further clarification, refer to: mutations must be synchronous

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

Using array map to create a centered table in a React web application

In my React project, I created a table using the array.map function. However, I'm facing an issue where the output of array.map is always aligned to the left, even before the table itself. I want to center the entire table. JSX: <div className=&qu ...

Working on asynchronous processing of Highland stream fragments

My current setup involves utilizing highland.js to process a file using a stream and extract content between specific delimiters. Additionally, I am incorporating async.js to perform a sequence of http requests. I am seeking a way to pass the output x fro ...

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

What is the reason for both the d3 line chart and bar chart being shown simultaneously?

On my website, I have implemented both a d3 bar chart and a line chart. You can view examples of them here: line_chart and bar_chart. However, in certain situations only one of the charts is displaying instead of both. Can anyone provide guidance on how ...

How can we store image file paths in MongoDB?

I'm currently working on developing a REST API using nodeJS, express, mongoose, and mongodb. I have successfully implemented file uploads with multer and saved the files to a folder. Now, I need to save the path of the uploaded file to a mongodb docum ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Automatically adjust text size within div based on width dimensions

Dealing with a specific issue here. I have a div that has a fixed width and height (227px x 27px). Inside this div, there is content such as First and Last name, which can vary in length. Sometimes the name is short, leaving empty space in the div, but som ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

HTML pages are free from any visible banner ads

There is a file named banners.js function addEvent(object, evName, fnName, cap) { if (object.attachEvent) object.attachEvent("on" + evName, fnName); else if (object.addEventListener) object.addEventListener(evName, fnName, cap); } ...

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

What is the best way to correctly showcase dynamic pages in ExpressJS?

Within my app.js file, there exists an array of objects that is defined as follows: var people = [ {name: "Henrique Melo", username: "heenrique", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a121f1408130b0f1 ...

The implementation of a custom event for jQuery rows is not functioning as expected

I need assistance with jQuery code to add click events only to columns in a row that have text in the first column. Specifically, I want to hide rows containing "1/" in the first column when clicked on for the first row. <table class="results"> < ...

What steps can I take to enable search functionality in Ckeditor's richcombo similar to the regular search feature in

I am currently developing a custom dropdown menu using the rich combo feature in CKEDITOR. One of my goals is to include a search functionality within the dropdown, such as a key press search or an input textbox search. This is how my dropdown box appear ...

What is the preset value for the payload in a vuex action?

Currently, I am utilizing an if-else statement in my Vuex action to set a default value for a payload property. Specifically, I check if the passed payload object contains a delay property; if it does not, I assign it a default value and handle appropriate ...

Encountering 404 errors in Nuxt application due to referencing non-existent JavaScript files

We've been working on our first Nuxt app for some time now and everything had been running smoothly. However, recently, a colleague made changes to the app and after pushing them to our staging server, the app suddenly stopped functioning properly. ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...