What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add a new item, the form is automatically filled with the details of the edited item. The form is displayed in a modal component.

Here is the code snippet related to the Modal:


 addItem(): void {
    this.isModalAdd = true;
    this.setModalVisible(true);
    this.form=this.new_form;
  }

  edit(item:Item):void{
        this.isModalAdd = false;
        this.setModalVisible(true);
        this.form = { ...item };
   }
<ItemsModal v-bind:form='form' v-bind:is-add='isModalAdd' v-bind:is-visible='isModalVisible' ></ItemsModal>

    <script lang="ts">
import { Component, Emit, Prop, Vue } from 'vue-property-decorator';
import { Action, State, namespace } from 'vuex-class';

import checkPassword from '@/utils/checkPassword';

const iStore = namespace('items');

@Component
export default class ItemsModal extends Vue {
  @Prop() form;
  @Prop() isAdd;
  @Prop() isVisible;
  @iStore.Action addItem;
  @iStore.Action editItem;
  @iStore.Action setModalVisible;
  @iStore.State isModalLoading;

 handleOk() {

    if (this.isAdd) {
      this.addItem(this.form);
    } else {
      this.editItem(this.form);
    }
  }

  handleClose() {
    this.setModalVisible(false);
  }
}
</script>


<template lang="pug">
b-modal(
  hide-header-close=true,
  :visible='isVisible',
  :cancel-title='$t("buttons.cancel")',
  :ok-disabled='isModalLoading',
  :ok-title='isModalLoading ? $t("buttons.sending") : isAdd ? $t("buttons.add") : $t("buttons.update")',
  :title='isAdd ? $t("users.add_user") : $t("users.edit_user")',
  @hide='handleClose',
  @ok.prevent='handleOk',
)
  b-form
    b-form-group(
      :label='$t("strings.name")'
      label-for='name',
    )
      b-form-input#name(
        type='text',
        v-model='form.name',
        maxlength='191',
        required,
      )
</template>

Answer №1

It appears that there might be some missing parts in your code. My suggestion is that after submitting your form, you should clear the form data. This means that after calling addItem(this.form), this.editItem(this.form), and setModalVisible(false), you should reset or nullify the properties of this.form. For example:

this.form = {}
or
this.form.name = null

Once you have completed the action with your API, make sure to empty or nullify the data related to that form.

editItem (form) {
  // perform operations with backend
  this.form = {}
}

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

Unable to retrieve this information using $http callback

I am currently working with angular 1.5 and typescript, but I am facing an issue where I cannot access the 'this' property from the callback returned by the $http promise. Whenever I try to access a private method from the callback, 'this&a ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

What is the best way to flatten a 2D array using TypeScript?

If I have an array structured like this: [0]: ["id_1"]: prop1: "abc" prop2: "def" ["id_2"]: prop1: "ghi" prop2: "jkl" [1]: ["id_3"]: prop1: "mno" prop2: "pqr" ["id_4"]: prop1: "stu" ...

Determine the data type of a parameter by referencing a prior parameter

Consider a scenario in my software where I have two distinct implementations of an Event Emitter. For instance: type HandlerA = (data: boolean) => void; type HandlerB = (data: number) => void; // HandlerB is somehow different from HandlerA type Eve ...

Contrast the different characteristics of string dynamic arrays in Angular 6

I am working with two arrays of strings. One array is a dynamic list of checkboxes and the other is the source to check if the item exists in the first array. I need to implement this dynamically using Angular 6, can you help me with this? Currently, the ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...

Is it possible to assign a variable in typescript using the interface as its type?

Here's the snippet of code I have written interface apiResult { Token: string; Result: any; } const result: apiResult = payload.Result; I am wondering about the significance of this code. Is it possible to assign a type from an interface to ...

Warning in TypeScript: TS7017 - The index signature of the object type is implictly assigned as type "any"

An alert for TypeScript warning is popping up with the message - Index signature of object type implicitly has any type The warning is triggered by the following code block: Object.keys(events).forEach(function (k: string) { const ev: ISumanEvent ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

Transferring object information to Backand using Ionic 2

I have developed a signup page using Ionic 2. In this signup page, I have included a dropdown menu for users to select their blood type. However, I am facing an issue where the selected blood type is not being sent to the Backand database as expected. I&ap ...

What causes the variable to be undefined in the method but not in the constructor in Typescript?

I am currently working on an application using AngularJS 1.4.9 with Typescript. In one of my controllers, I have injected the testManagementService service. The issue I'm facing is that while the testManagementService variable is defined as an object ...

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Error encountered with next-auth and the getServerSession function

Whenever I try to use the getServerSesssion function with all the necessary parameters, it results in a type error. In my code, I have the getServerAuthSession function defined as shown below: import { authOptions } from '@/pages/api/auth/[...nextauth ...

Is it possible to update the text within a button when hovering over it in Angular?

I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need to change the text content. <button type="submit" ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

Having trouble getting access to FormArray content for validation due to receiving null or undefined errors

CSS Tricks <form [formGroup]="newMovieForm"> <ng-container formArrayName="actors"> <ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index"> <div [formGroupN ...

The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure: my-package |- index.js |- index.d.ts |- package.json The index.d.ts file includes global declarations like: declare ...

Unexpected behavior in resolving modules with Babel (using node and typescript)

Within my node project setup, I utilize babel-plugin-module-resolver for managing relative paths efficiently. tsconfig.json { "compilerOptions": { "outDir": "build", "target": "es5", ...

Changing true/false values to Yes or No in Angular array output

I am working with an array that is structured as follows: { "Tasks": [ { "TaskID": 303691, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { ...