VueJS - V-for not updating after data changes, requires page refresh to display modifications

I'm experiencing an issue with this code - it doesn't seem to update or re-render the changes when I add or delete an entry. I have to refresh the page every time to see the modifications made.

Note: I am using ME(Vue)N stack.

Here is the code snippet:

<script>
import postService from '../../postService';
export default {
  name: 'postComponent',
  data() {
    return {
      posts: [],
      error: '',
      text: ''
    }
  },
  async created() {
    try {
      this.posts = await postService.getPosts();
    }catch(e) {
      this.error = e.message;
    }
  },
  methods: {
    async createPost() {
      await postService.insertPost(this.text)
      this.post =  await postService.getPosts();
      // alert(this.post,"---")
    },
    async deletePost(id) {
      await postService.deletePost(id)
      this.post = await postService.getPosts();
      
      // alert(this.post)
    }
  }
}
</script>
<template>
    <div class="container">
      <h1>Latest Posts</h1>
      <div class="create-post">
        <label for="create-post">input...</label>
        <input type="text" id="create-post" v-model="text" placeholder="Create a post">
        <button v-on:click="createPost">Post</button>
      </div>
      <!-- CREATE POST HERE -->
      <hr>
      <p class="error" v-if="error">{{error}}</p>
      <div class="posts-container">
        <div class="post"
          v-for="(post) in posts"
          v-bind:key="post._id"
          v-on:dblclick="deletePost(post._id)"
        >
        {{ `${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}

        <p class="text">{{ post.username }}</p>
        </div>
      </div>
    </div>
</template>

If there are any errors in the snippet, I apologize. Just wanted to showcase the code and unfortunately couldn't get the script to function within the sample {}.

Any assistance would be greatly appreciated. As a Vuejs beginner, I originally copied and typed this code while following a YouTube tutorial.

Answer №1

In your module, there is a data attribute called posts, however, you seem to be mistakenly assigning values to this.post in various sections of the script.

This could potentially be a typographical error. It's important to note that if this extra property (this.post) is not initially defined when the component loads, it will not automatically become reactive once created or modified.

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

Using regex in Javascript to find and match an ID within a string

JavaScript: var data='<div id="hai">this is div</div>'; I am looking to retrieve only the ID "hai" using a regular expression in JavaScript. The expected output should be, var id = regularexpression(data); The variable id should n ...

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

Tips for optimizing AJAX content for Google indexing

As I begin the process of developing a public website that utilizes client-side rendering with AngularJS, I have come across information suggesting that dynamically generated content may not be properly indexed by Google. This raises concerns about the imp ...

Enhancing User Interfaces with TypeScript Accordions

Looking for a way to expand the sub-menu when the SETTINGS menu is clicked using typescript. Here is the list structure: <li> <a href="#"> <i class="fa fa-cogs fa-fw"></i> <span>SETTINGS</span> </a> ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Apply jQuery styling to new select box on page in order to maintain consistent styling throughout

I've encountered an issue with my jQuery select box styling. It appears to work perfectly on the initial page load, but when new content containing a select box is dynamically loaded onto the page, the styling doesn't get applied to it. Can anyo ...

What is the best way to utilize node modules in the client-side while developing an Express application?

I'm currently working on a project with intl-tel-input integration within an environment utilizing express and ejs. In my app.js, I have configured app.use(express.static(path.join(__dirname, 'public')));, which allows Express to serve all ...

Tips for creating a two-tier selection filter system

I'm having an issue with this code. My objective is to create two filters for this table. The select element with id="myInput" should determine which rows appear in the table and apply the first filter. Here is the JavaScript code: function myFunctio ...

Animating the mobile menu transition using Bootstrap CSS

Can anyone help me with animating the mobile menu when I click the menu icon? This is what I have for the menu: .overlay-menu { position: fixed; display: none; z-index : 1040; width: 100vw; height: 100vh; background: rgba(0, 0,0, 0 ...

Displaying time text in input element due to browser bug

I am faced with a perplexing puzzle that has left me scratching my head. Here are two seemingly identical pieces of javascript code, but one behaves unexpectedly (take note of the Console.Log): Updates the UI once, then abruptly stops updating: http://js ...

Avoiding deadlock when utilizing std::future as a member variable

After migrating our app from Objective-C and Cocoa to C++, I encountered a shift in the way asynchronous tasks were handled. In Objective-C, I heavily relied on Grand Central Dispatch and the convenience of dispatch_async functions. Transitioning to C++1 ...

Morgan's logging only captures a fraction of the data to the file

My website uses Morgan and Express to handle REST APIs. I have set up the morgan-logger in my main.js file as follows: app.use(morgan('dev')); //logger app.use(morgan('dev', {stream: fs.createWriteStream('./access.log', {flag ...

Having Trouble Loading a Basic Scene in Three.js

I'm struggling to set up my HTML page with the basic scene because nothing is appearing. I can't seem to locate the required three.js file that I'm supposed to include in my js folder for referencing it as mentioned in the documentation (lin ...

Ways to hide an element when scrolling for a better user experience

I am encountering an issue with a custom icon element in my table. The icon is supposed to only be displayed when its specific row is hovered over. However, when I scroll down without moving my mouse, the hover state does not update and the icon remains on ...

Introducing Block Insert feature in React Draft-js - a powerful

How the Process Works: Upon hitting the spacebar, the Draft-JS editor queries the text content for a specific word. Subsequently, all instances of that word are enveloped in tags. The HTML is then converted back and the state of the Draft-JS editor is upd ...

Is there a way to configure my dropdown menu so that only one dropdown can be open at a time and it remains open when clicking on a <li> item?

I've been working on developing a dropdown menu that appears when clicked, rather than hovered over. I've managed to implement this functionality using JavaScript, and overall, it's working quite well. Currently, the menu shows or hides whe ...

Sending MongoDB query results directly to the Express server response

I am attempting to accomplish this task without any third-party dependencies, as I believe they are unnecessary. Please note that our architecture requirements mandate the use of MongoDB native instead of Mongoose (for reasons unknown). Essentially, I hav ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

Sequelize - Leveraging Associations in Where Clauses

Within sequelize, my setup includes boards and users with a many-to-many association structured like this: User.hasMany(Board, {through: BoardUsers}); Board.hasMany(User, {through:BoardUsers}); I'm trying to figure out if there's a way to use a ...