Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue?

Below is the code snippet from the template:

<template>
  <div class="container">
    <h1>Latest Posts</h1>
    <div class="create-post">
        <label for="create-post">Add new post...</label>
        <input type="text" id="create-post" v-model="text" placeholder="Create a post">
        <button v-on:click="createPost">Post!</button>
    </div>

    <hr>

    <p class="error" v-if="error">{{ error }}</p>

    <div class="posts-container">
      <div class="post" v-for="(post, index) in posts" v-bind:item="post" v-bind:index="index" v-bind:key="post._id">
        {{`${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
        <p class="text" id="example">{{post.text}}</p>
      </div>
    </div>

  </div>
</template>

And here's the script section of the code:


<script>
import PostService from '../PostService';

export default {
  name: 'PostComponent',
  data() {
    return {
      posts: [],
      error: '',
      text: ''
    }
  },
    computed: {
      postText: function() {
        return this.post.text
      }
    },
    watch: {

    },
  async created() {
    try {
      this.posts = await PostService.getPosts();
      console.log(this.$el.textContent) 
    } catch(err) {
      this.error = err.message;
    }
  },
  methods: {
    async createPost() {
      await PostService.insertPost(this.text);
      this.post = await PostService.getPosts();
    }
  }
}
</script>

Answer №1

It seems like there might be an issue with this line:

this.post = await PostService.getPosts();
It should actually be:
this.posts = await PostService.getPosts();
Check out this helpful Codepen link for reference. If changing that doesn't solve your problem, double-check that the PostService is returning correct objects.

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

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

What could be causing this jQuery color picker to malfunction when used inside a Bootstrap modal?

Currently, I am utilizing the fantastic jQuery color picker provided by Although it functions as expected in "normal" scenarios, I have encountered an issue where the picker fails to display when the input parent element is nested within a Bootstrap 3 mod ...

Is there an h1 heading on this page?

Trying to enhance the accessibility of a website by properly setting up the headers. Running into issues with ensuring they are in the correct order. If there is code that could be applied across all pages to set h1 if it doesn't exist (promoting h2, ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

What is the reason behind this strange alert coming from Vue / Vuetify / Vite?

Currently, I am setting up an array of Vuetify 'chips' that have the ability to drag data from one chip to another: <v-container id="endgrid" style="max-width: 300px; position: relative;"> <v-row v-for="(row,r) ...

Output the keycode to the console repeatedly

I'm currently facing a minor mental obstacle: I have a javascript function embedded in html that displays the keycode when a key is pressed. It's connected to a function that provides detailed information about the character and keycode being pre ...

Conditionally render a Vue component as a modal when the specified route metadata key is set to true

Currently, I am using vue-router and attempting to implement a specific functionality: The goal is to define within the router routes whether a component should be displayed in a modal or not. If rendered in a modal, all components beneath it (under modal ...

Is there a way to resolve the issue of my localStorage getting overridden on page refresh?

I am currently working on a simple React app and encountering an issue with the localStorage. Whenever I refresh the page, the todo list stored in the localStorage disappears. How can I ensure that the todos remain visible even after a refresh? Any sugges ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

The preventDefault function fails to work in Firefox

My input is called shop_cat_edit and I've included the following code. However, it seems to work fine in IE but doesn't work in FireFox. Can anyone help me figure out what's wrong? $('[name=shop_cat_edit]').on('click',fu ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

Trouble accessing Silverlight site due to incomplete loading

There is a site known as that consists of a Silverlight application. Strangely, this site loads on all other computers except mine. I keep encountering the following error: An Error occurred in the Silverlight Application: String was not recognized as a ...

Employ a class function within router.get

I'm a beginner with node.js and I'm running into an issue when trying to use a class method in the router.get callback function. Can someone assist me with this problem? Route.get() is expecting a callback function but received a [object object] ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Bookshelfjs fails to return a promise when updating multiple data

I am facing an issue when trying to update multiple rows in my database. The problem lies in the fact that the promise does not return anything, even though the data is successfully saved. Below is a snippet of my code: doUpdate: Promise.method(function ...

Retrieve a value using the jQuery each() method

Hello, I am a beginner in JavaScript and I need help with extracting values from JSON and adding them to an array. My goal is to be able to parse this array using another function later on. However, I'm struggling with returning the array after adding ...

When attempting to insert a date into a MySQL database using React.js, I encountered an issue with the date format

Hey everyone, I have set the input date to dd/mm/yyyy format using moment(donors.donateDate).format('DD-MM-YYYY'). However, when I click the submit button, an error is displayed in the console stating: The specified value "23-03-2022" ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...