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

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

The application is unable to recognize the CSS file

I am facing an issue where the design of my app is not displaying, even though the CSS file is located in the same folder. I'm unsure about what mistake I might have made! import React from 'react'; import classes from './Burger.css&ap ...

Tips for changing the visibility of a div within table rows upon clicking

Struggling to solve this jQuery issue with a table that displays numbers on each row. I want to be able to click on one of the numbers, which is a href link, and toggle only the corresponding div called "test" instead of toggling all rows at once. How can ...

Activate the Click in the Span Element with no Matching ID to the Final Segment of the URL

I'm facing an issue with triggering the click event on a specific span that lacks an id attribute. This particular span has an empty ID and doesn't respond when I try to click the back or forward buttons in the browser. All other spans trigger th ...

Issue with hydration in Vue/Nuxt layout due to client-side authentication and computed property

In my app (using vue/nuxt 3), the user authentication state is stored in localStorage. This means that it is only accessible on the client side, and prerendered pages always display unauthenticated content. The client will switch to displaying authenticate ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

What steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...

What is the method for triggering a JavaScript function by clicking a button within a CakePHP application?

<button type="button" id="addleetdata" class="btn btn-primary addleetdata float-left">Add</button> JS File $("#addleetdata").click(function () { console.log("entering into function") startLoading(); console.log("editin ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

What is the best way to utilize RxJs with jQuery's ajax function?

Here is how I've set it up: Rx.Observable.fromPromise($.ajax({ url: url + postal_value + '&types=(regions)&location=51.509865,-0.118092&key=' + key, type: "GET", datatype: "json" })); However, the aj ...

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

-g option must be enabled for jscoverage to function properly

To install jscoverage globally, use the following command: npm install jscoverage -g Do you know what purpose the -g option serves? Without using the -g option, my system does not recognize jscoverage as a valid command. ...

The data retrieved from the PHP script is not accessible within the main Vue instance

I am currently working on a Vue.js component for a modal window. Once the user fills out all the necessary data in the fields, I need to achieve the following: Send the data to the server. Apply a timeout to show the user that the data is being sent (by ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Unable to locate child after adding element to HTML

I have been attempting to add a child element to my HTML document, and although I can see it in the source code, it doesn't display on the screen as expected. It's quite baffling. Here is the HTML code snippet: <!DOCTYPE html> <html> ...

The magical form component in React using TypeScript with the powerful react-final-form

My goal is to develop a 3-step form using react-final-form with TypeScript in React.js. I found inspiration from codesandbox, but I am encountering an issue with the const static Page. I am struggling to convert it to TypeScript and honestly, I don't ...

Submit the form without displaying any output in the browser, not even in the view source code

I have a basic form that needs to be submitted multiple times, but I want the submission process to be hidden from the browser. Simply using "hidden" or "display:none" won't completely hide the form code when viewing the page source. I tried using PHP ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...