Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template>
  <div class="card m-3">
    <div class="card-body">
      <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, isSubmitting, handleReset }">
         <div class="form-group col-5">
            <Field name="id" type="hidden" class="form-control"  v-model="id" />
            <Field name="title" type="text" class="form-control" :placeholder="'Title'" v-model="post.title"  :class="{ 'is-invalid': errors.title }"/>
            <ErrorMessage name="title" />
          </div>
          <br/>
           <div class="form-group col-5">
            <Field name="author" type="text" class="form-control" :placeholder="'Author'"  v-model="post.author" :class="{ 'is-invalid': errors.author }"/>
            <ErrorMessage name="author" />
          </div>
          <br /><br />
          <b-button variant="primary" type="submit" :disabled="isSubmitting" :class="{ 'submitting': isSubmitting }"> {{ buttonText }}</b-button>
          &nbsp;&nbsp;&nbsp;
          <b-button variant="warning" @click="handleReset">Reset</b-button><br/>
      </Form>
    </div>
  </div>
  <br />
  <br />
    <table border="1" cellpadding="10" v-if="list != undefined && list.length">
      <tr>
        <td>Title</td>
        <td>Author</td>
        <td>Action</td>
      </tr>
      <tr v-for="post in list" :key="post.id">
        <td>{{ post.title }}</td>
        <td>{{ post.author }}</td>
        <td>
          <b-button variant="info" v-on:click="getEditUserDetails(post.id)"
            >Edit</b-button
          >
        </td>
      </tr>
    </table>
    <h1 v-else>No Records Found</h1>
</template>


<script>
import { createApp } from "vue";
import VueAxios from "vue-axios";
import axios from "axios";
import App from "../App.vue";
import { Form, Field, ErrorMessage } from "vee-validate";
import * as Yup from "yup";

const app = createApp(App);
app.use(VueAxios, axios);

export default {
  name: "Posts",
  components: {
    Form,
    Field,
    ErrorMessage,
  },
  data() {
    return {
      post: {
        title: null,
        author: null,
      },
      list: undefined,
      isEditMode: false,
      id: null,
      buttonText: "Add",
    };
  },
  computed:{
    schema() {
      return Yup.object({
      title: Yup.string().required("Title is required").nullable(),
      author: Yup.string().required("Author is required").nullable(),
    });
    },
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    submitData() {
      if (this.isEditMode) {
        axios
          .put("http://localhost:3000/posts/" + this.id, this.post)
          .then(() => {
            this.isEditMode = false;
            this.buttonText = this.isEditMode ? "Edit" : "Add";
            this.id = null;
        });
      } else {
        axios.post("http://localhost:3000/posts", this.post).then(() => {
          this.buttonText = this.isEditMode ? "Edit" : "Add";
        });
      }
      this.getUsers();
    },
    getUsers() {
      axios.get("http://localhost:3000/posts").then((result) => {
        this.list = result.data;
      });
    },
    getEditUserDetails(id) {
      axios.get("http://localhost:3000/posts/" + id).then((result) => {
        this.id = result.data.id;
        this.post.title = result.data.title;
        this.post.author = result.data.author;
        this.isEditMode = true;
        this.buttonText = this.isEditMode ? "Edit" : "Add";
      });
    },
  },
};
</script>

My vue/cli version is 4.5.13, vee-validate version is 4.4.11 and vue-axios version is 3.3.6

I am experiencing an issue where newly added data does not update in the input fields immediately when trying to edit the same data. However, selecting another available post before going back to the added post resolves the issue.

Answer №1

Your reactivity may be decreasing due to the list: undefined data issue. It seems like you are getting an array from your axios.get() call.

To resolve this, consider the following adjustments:

 data() {
   return {
      post: {
        title: null,
        author: null,
      },
      list: [], // Make sure to define a default value as an array
      isEditMode: false,
      id: null,
      buttonText: "Add",
    };
  },

....

methods: {
  ....
  
    getUsers() {
      axios.get("http://localhost:3000/posts").then((result) => {
        this.list = [ ...result.data]
      })
    },
}

For displaying in a table format:

<table border="1" cellpadding="10" v-if="list.length">
      <tr>
        <td>Title</td>
        <td>Author</td>
        <td>Action</td>
      </tr>
      <tr v-for="post in list" :key="post.id">
        <td>{{ post.title }}</td>
        <td>{{ post.author }}</td>
        <td>
          <b-button variant="info" v-on:click="getEditUserDetails(post.id)"
            >Edit</b-button
          >
        </td>
      </tr>
    </table>
    <h1 v-else>No Records Found</h1>

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

In jQuery, there seems to be an issue where the click event is not functioning properly on an element that has been

I am using jQuery to append items, but I am having trouble binding events to the appended items. My appending code looks like this: var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px; ...

What causes the child component to re-render when only the prop is changed and useCallback is used?

Child component will only re-render if its prop (numberModifier) is changed. The numberModifier uses useCallback with no dependencies, so it remains constant. To test this, I alter the value of "online" in the Application component which is a prop of Pare ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

The output for each function is consistently the same for every record

Implementing a foreach loop to send data and display it in the success function of an AJAX call is functioning smoothly. Recently, I made a modification to the code by introducing a new data-attribute which contains the $creator variable. Here's how ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Using Nativescript VueJS to toggle the button state with Axios

Check out my code snippet: <Button text="Login" @tap="submit" class="btn btn-primary m-t-20" :isEnabled="isTappable" /> submit(event) { this.isTappable = false; let eventListener = this.isTappable; a ...

Activating the CSS :active selector for elements other than anchor tags

How can I activate the :active state for non-anchor elements using JavaScript (jQuery)? After reading through Section 5.11.3 of the W3C CSS2 specification in relation to the :hover pseudo selector in hopes of triggering the activation of an element, I stu ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

When providing the index.html file using express.js, remember to include the user-agent header

When using my Express.js app to render my index.html page, I want to customize the http 'User-Agent' header. </p> <p>I've tried this method without success:</p> <pre><code>req.headers['user-agent'] = ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

Title of the most recently created file on GitHub

Being new to web designing and javascript, I am seeking help in understanding how to display the latest PDF file in my small website hosted on GitHub. Despite successfully displaying a PDF file, I encountered difficulties when attempting to showcase the mo ...

I am encountering an issue with my function where I aim to prevent the creation of a node using duplicate coordinates

Trying to avoid creating a node with existing coordinates, I implemented a check in my code. The check is supposed to determine if there are any nodes with the same coordinates already present. However, it seems that the check is not working as expected an ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Create a form with two submission buttons along with a captcha verification system

I'm currently developing a booking page form that requires a unique functionality. I need a single form where clients can enter their information, followed by two submit buttons at the bottom. The first button should hold their reservation for 72 hour ...

Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion ...

Attempting to compare the HTML datetime with the current time in order to implement conditional formatting

I am working with a SharePoint discussion list that includes a field named "Last Updated." My goal is to identify and highlight rows where the last update was more than 1 hour ago. Here is my current approach: <html> <head> <sc ...

Vue3 is throwing an error stating that it cannot read the property 'insertBefore' of null

Whenever I attempt to update my data fields in vuejs, I encounter this error. data() { return { form : useForm({ imageFile : null, img_id : null, }), product_images : this.images, } }, After a succes ...