Vue.js array successfully updated based on the current status of the API

I am a beginner in Vue.js and I am working on calling an API. It is functioning perfectly, but I need to update the Vue.js array based on a condition of the API response. However, when trying to do so, I encounter the error "do not mutate vuex store state outside mutation handlers." How can I resolve this issue?

 axios.post(baseUrl+'/api/v1/addProductWishlist', pitem,
                {headers: {
                'Authorization': 'Bearer ' + x,
               'Content-Type':'application/json'
              }
              }).then(r => {
                  if(r.data.status == 202)
                  {
                    
                  }
                  else{
                    state.cartItems.push(payload);

                  }
              });

Answer №2

It is crucial to adhere to the correct pattern when using Vuex for state management. Updating the state should only be done from within a mutation, as this is key to maintaining reactivity and ensuring predictability in large applications. Failure to follow this guideline can result in issues with tracking changes to the state.

A recommended practice is to organize mutations, actions, and API calls into separate files. Actions serve as functionality managers, triggering API calls from an external file before updating the state via mutations.

// actions.js
{
  myAction: async ({ commit }) => {
    const response = await myApiCall();
    if (response.data.status == 202) { ... }
    else {
      commit('ADD_CART_ITEM', response.item)
    }
  }
}

// api.js
export function myApiCall() {
  return axios.post(...)
}

// mutations.js
{
  ADD_CART_ITEM: (state, payload) => state.cartItems.push(payload);
}

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

Creating a table-style format from a JSON string fetched via AJAX: a step-by-step guide

Hi, I recently started learning web programming and I've been facing some challenges with using AJAX to parse data as a string and display it in a table. [{"source":"1","name":"random","amount":"5"},{"source":"1","name":"random","amount":"5"}] After ...

Incorporate sweetalert2 into your node.js and express.js project

Trying to incorporate sweetalert2 into my Node.js and Express.js project has not been successful so far. The error message I keep encountering is: swal is not defined ReferenceError: swal is not defined Here are my configurations index.js var express ...

Creating a data structure using jQuery/JavaScript when submitting a form - a guide

Currently, I am attempting to gather form input values and organize them into an array of objects that will then be sent to MongoDB. However, I am facing difficulty in figuring out how to include an array within the objects (refer to the comment in the cod ...

Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it' ...

What is the solution to the error message "A TypeError was encountered in the current module: e.parse is not a function"?

Can someone please help me resolve this Vue Js error I am encountering in Shopware 6 Administration? The issue pertains to selecting a column in the database table using a module. Note: Below is the complete code snippet. I am attempting to retrieve data ...

During the ng build process, an error is encountered stating, "Cannot read the property 'kind' of undefined."

Currently, I am working on a project that requires me to utilize ng build --prod in order to build a client. However, each time I run ng build --prod, I encounter the same persistent error message: ERROR in Cannot read property 'kind' of undefin ...

Chose to conceal all child elements, but is unable to reveal all elements when clicked

Currently, I am in the process of creating a jQuery accordion by following the tutorial provided on css-tricks at this link. After making some modifications to the code, I was able to hide all the elements within the parent element. However, upon clicking, ...

What could be causing a successful return from JQuery Ajax but still showing an error in Firebug within a PHP application?

I'm encountering an issue with my form submission and jQuery validator plugin. Everything seems to be working fine until I reach the submit handler in my jQuery code: submitHandler: function (form) { $.ajax({ type: "POST", url: ...

Error: The function a.then is not recognized during the production compilation process

I am currently facing an issue with compiling my Vue app in production using npm run build (specifically vite build). Once I attempt to serve the app on my server using the /dist folder, everything functions perfectly fine. I can send fetch requests, navi ...

What are the steps to resolve a peer dependency problem with npm?

I am facing a conflict in my package.json file with the following modules: react-router requires react 0.13.x redbox-react requires react@>=0.13.2 || ^0.14.0-rc1 After running npm install react, I ended up with version <a href="/cdn-cgi/l/emai ...

Struggling to implement v-for on a table row to display a child component with multiple columns

My code is throwing this error: The component template must have only one root element. In the parent component, I have: <tr v-for="item in items" :key="item.id"> <Item :item="item" /> And in the Item component: <td> hello < ...

Mouse position-based scrolling that preserves click events in the forefront while scrolling

Within a larger div, I have a very wide inner div that scrolls left and right based on the position of the mouse. I found the code for this from an answer at There are two transparent divs above everything else, which capture the mouse position to determ ...

Using Polymer, assign specific values to an array of data in Firebase

Issue: I am attempting to manage multiple games on Firebase with unique IDs, but encountering difficulties fetching the data as Objects instead of Arrays using <firebase-collection>. Two-way binding is proving challenging with Polymer. Is there ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

What is the best way to transform a velocity array [x, y, z] into a formatted string for insertion into a database?

I need help figuring out how to store a velocity vector that is declared as follows: me.vel = [0, 0, 0]; I want to save this velocity vector into a MySQL database. I believe it needs to be converted into a string for storage purposes. However, I am unsu ...

The Safari browser is currently having trouble loading the data sent back from the server

After successfully developing and deploying my website carspeedyrental.com, I received reports from some clients indicating that the website does not display available cars on the iPhone Safari browser. Interestingly, when tested on various browsers on A ...

Does Eslint's no-restricted-imports rule only limit imports from the package's root directory?

For example, I'm looking to limit the usage of importing react-use, while still permitting react-use/lib/usePrevious. I attempted this: rules: { 'no-restricted-imports': [2, { patterns: [ 'react-use', ] }], }, As ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

Is there a way to prevent an item from being selected in a Select component when the first letter of the option is pressed?

I'm currently working with the material UI Select component and I'm attempting to create a filter within it that will only display items matching the user's input. Below is a simplified example of my current project: function App() { con ...