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

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

Using Selenium Webdriver to initiate the play function of a video by clicking on the control

Is there a way to play the video on this page by clicking the play button? I noticed a 'playpause' control in the JavaScript, but I'm unsure how to activate it. <div id="videoModal" class="reveal-modal expand open" style="display: block ...

Send the component template and functions when triggering an expanded view in a material dialog

While striving to adhere to DRY coding principles, I've encountered a dilemma involving a particular use case. The task at hand is to display an expanded view of a component within a dialog box. This component presents JSON records in a paginated list ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

Tips for setting a blank date field as the default value in a ui-datepicker in Vue.js

I'm working with a ui-datepicker in vue.js and I need to have the field empty or blank by default. <ui-datepicker label="Date" v-model="searchDate" :custom-formatter="picker9Formatter" :lang="picker12Lang"> </ui-datepicke ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...

Instructions for capturing multi-dimensional arrays using forms in Vue

I have a snippet of code that looks like this: <div class="form-item"> <label for="list-0"><?php _e('List 0', 'test'); ?></label> <input name="list[0]" type="text" id="list-0" value=""> </div> &l ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...

Clicking on the user will reveal a modal containing all of the user's detailed information

**I am trying to pass the correct user data to the modal ViewUser component, but it keeps displaying the same user regardless of which user I click on. How can I specify the specific user whose data should be shown? I am sending the user information as a ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

What is a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...

Is there a way to switch between showing and hiding all images rather than just hiding them one by one?

Is there a way I can modify my code to create a button that toggles between hiding and showing all images (under the user_upload class), instead of just hiding them? function hidei(id) { $('.user_upload').toggle(); Any suggestions would be grea ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Guide on how to streamline JSON output from aggregation result

I have written a NodeJs api using mongo db aggregation to obtain some output. However, the result I received is not what I expected. Can anyone help me figure out how to get the desired output? app.get('/polute', function (req, res) { Light. ...

Defining a property of an object within a Vue Class

If I were to write it in JavaScript version: export default { data() { return { users: {} } } } However, when using a class style component with vue-property-decorator: @Component export default class Login extends Vue { public title ...