Revise the form used to edit data stored in Vuex and accessed through computed properties

My form component is used for client registration and editing purposes. Upon creation of the form component, I check if there is an ID in the URL to determine which type of form to display. If no ID is present (indicating a new client registration), all fields should be empty. If an ID is found in the URL, I make an Axios request to load the client information, store it in Vuex, and display the data in the fields for modification.

     <Form enctype="multipart/form-data" @submit="$emit('submit')">
         <validation-provider
                     name="Company name"
                          >
                      <v-text-field
                      v-model="details.company_name"
                              label="Company name"
                            />
                  <span class="text-sm text-red-500">{{ errors[0] }}</span>
          </validation-provider>
     <validation-provider
                     name="Company email"
                          >
                      <v-text-field
                      v-model="details.email"
                              label="Company email"
                            />
                  <span class="text-sm text-red-500">{{ errors[1] }}</span>
          </validation-provider>
     <validation-provider
                     name="Company phone"
                          >
                      <v-text-field
                      v-model="details.phone"
                              label="Company phone"
                            />
                  <span class="text-sm text-red-500">{{ errors[2] }}</span>
          </validation-provider>
        ...

Next, I define the data properties:

    data: function () {
        return {
          details: {
            type: Object,
            default: () => ({})
    
          },

In the create method, I use

await this.$store.dispatch("clients/getClientById", { id: id})
to retrieve client information

The issue I'm encountering is that after retrieving the client via computed, I am unsure how to bind them with v-model to send them using FormData or edit them. Can someone please provide guidance?

I tried the following approach but encountered an error stating

Error: [vuex] do not mutate vuex store state outside mutation handlers
whenever I input something in the field.

    async getClientById(id){
          await this.$store.dispatch("clients/getClientById", {
            id: id})
            .then(res => {
            if (res.status === 200 ){
              let clientData = res.data.data
              this.details = clientData
              this.status = clientData.status
            }
          })

Answer №1

Top Answer

It seems like your previous attempt didn't work because objects are passed by reference in JavaScript. This means that when you modify an object outside of a mutation, it directly affects the object inside Vuex state, which is not allowed in strict mode.

To solve this issue, you can make a copy of the object. Keep in mind that this approach only works if the members of the object are simple values, not objects:

if (res.status === 200 ){
          let clientData = { ...res.data.data }
          this.details = clientData
          this.status = clientData.status
        }

Important Tips for Forms

When working on Create/Edit forms, consider these key features:

  1. Include Save/Cancel buttons to allow users to easily undo changes.
  2. Implement validation to ensure that only valid data can be saved.

One effective way to handle forms is by first copying all data from Vuex into local data of the form component and binding inputs to the local data. This approach offers several advantages:

  1. Changes made by the user will only affect local data, leaving the original data in Vuex untouched. Closing the form discards all local data, making implementing "Cancel" straightforward.

  2. Implementing "Save" becomes simpler as well - validate the data and then commit the changes using a mutation to update the Vuex store.

  3. Preventing other components from accessing potentially invalid intermediate data is crucial when data is used in multiple parts of the application.

  4. Binding form controls to local reactive data simplifies form component code compared to directly binding to Vuex state.

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

What is the process for placing a component on the right side of the sidebar?

Here is the code snippet I am working with: <template> <div class="main"> <sidebar /> <router-view /> </div> </template> The sidebar has a width of 260px. I need to ensure that any comp ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

I'm encountering an issue where Bulma is taking precedence over the CSS of my Vue3

In my Vue CLI 3 project, I'm utilizing Bulma and have included the import in the 'index.js' file like so: import { createApp } from 'vue' import App from './App.vue' import router from './router' require('@ ...

Activating a function that requires locating a dynamically loaded element on the webpage using AJAX

I have a unique page on my website that allows users to make edits. Whenever they click on an item, the edit form is seamlessly loaded into a specialized section of the page using AJAX. Depending on the chosen item, the form fields are already prefilled w ...

Creating Virtual Nodes from a string with HTML tags in Vue 2.5: A Step-by-Step Guide

Having some trouble creating a functional component that displays the Feather Icons package - I'm stuck on the final step. Here's what I have so far: This is my FeatherIcon.vue component. <script> const feather = require("feather-icons"); ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResultSe ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...

Gulp does not generate any files

Hey there, I'm brand new to using node.js and coding in general. I recently attempted to convert SCSS to CSS using gulp. My gulpfile.js seems to be correct, but when I try running "gulp styles" in the node.js command prompt, I receive the following ou ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Sending information from a Vuex module to a component following an axios request

I'm currently working on developing a Vue.js based application. Here's the scenario I'm facing: I have a component with a popup where users can create an 'expense' entry. Upon clicking the 'save' button, a function in the ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Issue with BrowserRouter, improperly looping through the array using map

Encountering an issue with importing content in my React app project using <BrowserRouter>. Within the app, there are 3 Material-UI Tabs: /lights, /animations, /settings. <Switch> <Route path="/lights" component={LightsMenu} /> ...