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

How can I use a dropdown with checkbox to toggle the visibility of a specific div in React?

I have come across a relevant question, but I am struggling to apply it to multiple divs. I haven't found a solution that quite fits my needs. Show or hide element in React Currently, I am using the dropdown with checkboxes from MUI. I am seeking a ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

Grant permission to access a website even when domain filtering is enabled

I recently created a basic web application that utilizes the YouTube API for performing search and displaying results. $.ajax({ url: 'http://gdata.youtube.com/feeds/mobile/videos?alt=json-in-script&q=' + q, dataType: 'jsonp&apos ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

How can I use Node.js Express to send a response in a file format like JavaScript or another type?

Currently, I have a piece of code that successfully reads the 'example.js' file and sends it to the client as requested. app.get('/mods/example.js', function(req, res) { fs.readFile('./mods/example.js', {encod ...

Vue.js template is failing to properly render hyperlinks, although basic string output is functioning as expected

Whenever I print attrib.link, everything works perfectly fine, <div v-for="attrib in attributes"> {{ attrib.link }} </div> However, when I try: <div v-for="attrib in attributes"> <a target='_blank' href={{ attrib.link } ...

When instance data is altered during an ajax submission, the input data is reset

Within my Vue instance, I have implemented the following method: ajaxSubmit: function(event) { this.loader = true; var form = event.target; var action = form.getAttribute('action'); var data = new FormData(f ...

Updating input text value using jQuery - Chrome extension

I have been attempting to modify the input value on a specific website using a Chrome extension. To achieve this, I am utilizing jQuery in my content script. While it is effective in most scenarios, I encountered difficulty changing the input value when ...

Simple guide to returning values from PHP using AJAX

I have a script on my login page that uses AJAX to send data to PHP, and PHP then returns whether the login was successful or not. I am curious about how I can modify my scripts to also send back two variables and receive them in my login JavaScript so tha ...

Encountered an issue during the installation process of the CoreUI Laravel Vue admin panel template

I recently downloaded the CoreUI Laravel VueJS admin panel template from the official GitHub repository. After unzipping the file on my Wampserver64, I proceeded to install the necessary dependencies by running npm install and composer install commands suc ...

What is the most effective method for transmitting data within your Vue3 application?

What is the best way to pass data between Vue components? I am looking for a method that allows me to fetch data from the backend once and share it across my project seamlessly, but I can't seem to find the right approach. sessionStorage: It works we ...

Troubleshooting issue: Webpack dev server's Hot Module Replacement not functioning correctly when

I've been working on a Vue 2 application that is mostly JavaScript, and now I am looking to incorporate some new TypeScript modules and components into it. Everything runs smoothly when I start the webpack dev server. However, whenever I make a chang ...

Installing different versions of a package in npm can be done by loading multiple versions

I am in the process of setting up a web API and I want to provide support for various versions of the underlying library. In essence, I would like to access it through: where x.y.z represents the version of the library I am utilizing. Using npm for mana ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

Node.js (Express), passport.js, mongoose.js, and Android app all have in common the HTTP Error 307 - Temporary redirect

I am currently constructing a REST Api using Node.js (Express.js and Moongose.js). I have a single post route that takes JSON data and redirects it to the signup page (/app/signup) if the user is a first-time user (not found in the database), or to the log ...

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Tips on how to bring in .js that has brought in .json from an html file

English is not my first language, and I struggle with it, but I did my best. I am attempting to include a js file that imports json from an html .js import menus from '../json/menus.json'; (function () { function parseMenu(ul, menu) { fo ...

Cross-origin resource sharing error detected in development environment; functions properly when tested on local machine

Struggling with making an API call from a Vue application to a .NET Core web API. It works fine locally, but when we try it on our first dev environment, we encounter this issue: Access to XMLHttpRequest at '' from origin '' has ...

I can't seem to get my JavaScript to connect to my HTML file. What should I do next?

I'm facing a major issue at the moment. My HTML file doesn't seem to be linking properly with my JavaScript file, even though they are located in the same folder. The script link is correctly placed in the HTML file, but for some reason, it just ...