Discover the secret to instantly displaying comments after submission without refreshing the page in VueJS

Is there a way to display the comment instantly after clicking on the submit button, without having to refresh the page? Currently, the comment is saved to the database but only appears after refreshing. I'm looking for a solution or syntax that can help achieve this.

        <div class="form-group">
          <h1>Review Here</h1>
          <textarea
            class="form-control mb-2"
            rows="3"
            v-model="getReview.getDescription"
          ></textarea>
          <div class="row">
            <div class="col-md-6">
              <div id="ratings">
                <div id="like" class="rating">
                  <input
                    type="radio"
                    value="5"
                    v-model="getReview.getRating"
                  >
                  <input
                    type="radio"
                    value="4"
                    v-model="getReview.getRating"
                  >
                  <input
                    type="radio"
                    value="3"
                    v-model="getReview.getRating"
                  >
                  <input
                    type="radio"
                    value="2"
                    v-model="getReview.getRating"
                  >
                  <input
                    type="radio"
                    value="1"
                    v-model="getReview.getRating"
                  >
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <button v-on:click="addNewReview()">Submit</button>
            </div>

I am trying to add new comment data to the reviews array with the following script:

<script>
export default {
  props: ["id", "usernow"],
  data() {
    return {
      reviews: [],
      orgData: {
        name_org: "",
        headerpic: "",
        description: ""
      },
      getReview: {
        getOrgId: this.id,
        getUserId: this.usernow.id,
        getRating: "",
        getDescription: ""
      }
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    addNewReview() {
      if (
        this.getReview.getDescription != "" &&
        this.getReview.getRating != 0
      ) {
        axios.post("/api/reviews", {
          org_id: this.getReview.getOrgId,
          user_id: this.getReview.getUserId,
          description: this.getReview.getDescription,
          rating: this.getReview.getRating
        });
        this.getReview.getDescription = "";
        this.getReview.getRating = 0;
        alert("OK");
      } else {
        alert("Please Review and rate this");
      }
    },
    getData() {
      axios.get("/api/listorgs/" + this.id).then(response => {
        var ArrayData = response.data;
        this.orgData = ArrayData.ListOrg;
        this.reviews = ArrayData.Review.map(review => {
          return {
            description: review.description,
            user: review.user,
            rating: review.rating,
            created_at: review.created_at
          };
        });
      });
    }
  }
};
</script>

Answer №1

After reviewing the getData() function, it appears that each review item should adhere to this structure:

{
  description,
  user,
  rating,
  created_at
}

To incorporate a new review into the system using the addNewReview() method, you need to transform the getReview object into the specified format and then add this new object to the reviews[] array:

addNewReview() {
  if (...) {
    axios.post(...);

    const newReview = {
      description: this.getReview.getDescription,
      user: this.getReview.getUserId,
      rating: this.getReview.getRating,
      created_at: new Date()
    };
    this.reviews.push(newReview);

    this.getReview.getDescription = '';
    this.getReview.getRating = 0;

  } else {
    ...
  }
}

new Vue({
  el: '#app',
  data: () => ({
    reviews: [],
    getReview: {
      getOrgId: '',
      getUserId: 'john123',
      getRating: 3,
      getDescription: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet, vero quisquam laboriosam magni enim, deserunt provident facilis eaque, alias fuga velit suscipit dolorum. Modi repudiandae nihil in incidunt quis placeat.',
    }
  }),
  methods: {
    addReview(review) {
      this.reviews.push({
        created_at: new Date(),
        user: review.getUserId,
        description: review.getDescription,
        rating: review.getRating
      })
    },
    submitReview() {
      this.addReview({
        getUserId: this.getReview.getUserId,
        getDescription: this.getReview.getDescription,
        getRating: this.getReview.getRating,
      })
    }
  }
})
.reviews {
  list-style: none;
}
.review {
  border: solid 1px #ccc;
  padding: 1em;
  margin: 0.5em;
  border-radius: 3px;
  max-width: 450px;
}
.user {
  font-weight: bold;
}
created_at {
  font-size: 0.8em;
  color: #888;
}
.description {
  font-style: italic;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a4c4f5f7a08140c140b0a">[email protected]</a>"></script>

<div id="app">
  <form action="#" @submit.prevent="submitReview">
    <div>
      <label>User
        <input type="text" v-model="getReview.getUserId" required>
      </label>
    </div>
    <div>
      <label>Rating
        <input type="number" min="1" max="5" v-model.number="getReview.getRating" required>
      </label>
    </div>
    <div>
      <label>Comment
        <input type="text" v-model="getReview.getDescription"></input>
      </label>
    </div>

    <button type="submit">Submit review</button>
  </form>

  <h3>Reviews ({{reviews.length}})</h3>
  <ul class="reviews">
    <li class="review" v-for="review in reviews">
      <div>
        <div class="rating">
          <span v-for="n in review.rating">⭐</span>
        </div>
        <span class="user">{{review.user}}</span>
        <div class="created_at">{{review.created_at}}</div>
      </div>
      <p class="description">{{review.description}}</p>
    </li>
  </ul>
</div>

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

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

The backend API does not receive the correct value from the checkbox

I'm having an issue with my registration page in ReactJS. There is a checkbox field called isadult. After clicking on the Register button and saving the data to a MongoDB database, the value of isadult shows up as [Object object] instead of True or Fa ...

What is the best way to set up webpack to exclude a non-existent asset in my scss files?

I am encountering an issue while compiling my scss file. Within the .scss file, I have the following code: body { background-image: url("/static/background.webp"); } The error message I'm seeing is as follows: error in . ...

What are some solutions for resolving a background image that fails to load?

HTML: `<div class="food-imagesM imagecontainer"> <!--Page info decoration etc.--> </div>` CSS: `.food-imagesM.imagecontainer{ background-image: url("/Images/Caribbean-food-Menu.jpg"); background-repeat: no-repeat; backgroun ...

Why is the image auto-swapping script failing to display images frequently?

I have a script that is currently running to rotate between two different logos on my webpage. What I am attempting to achieve is for the page to load and then seamlessly transition from one image to the other without any blank space. Below is the code I ...

Managing user sessions in Node.js

What is the best way to manage SESSIONS in Node.js? Specifically, I am interested in storing a UserID in a session using Node.js. How can this be accomplished, and is it possible to access that Node.js session in PHP as well? I am looking for an equivale ...

My chart's data gets misaligned when I resize the window, causing issues with the d3

I have 5 HTML elements with the class "container" that will contain 5 SVG images. The ids of these elements are generated programmatically and consist of numbers: <div id="svg-container-total"></div> <div id="svg-container-3"></div> ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

The Bootstrap navigation menu fails to extend the parent div when toggled

When I toggle the button to show the menu on small screens, the menu overflows the parent div with id=contents instead of pushing it down. How can this issue be fixed? Here is the code: <body> <nav id="header" class="navbar navbar-default"& ...

Top recommendation for ensuring that a component is not being displayed

Imagine a scenario where a component returns null in the render method based on a specific prop. How can you effectively use expect to ensure that the component is not rendered? For example: import React from 'react'; import { render, fireEvent ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

I'm having trouble understanding this JSON array. It appears to be structured like an object. How should I

Seeking assistance. Despite my efforts, I haven't been able to figure out how to parse this JSON array into individual PHP variables and insert it into a MySQL table: stdClass Object ( [status] => ok [search] => search_data [paginat ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

Exploring Next.js with getStaticPaths for multi-language support

In my current Next.js project, I am working on implementing multiple locales for dynamic pages using i18n. Within my next.config.js file, the following configuration is set: module.exports = { i18n: { locales: ["en-US", "da-DK", "se-SE", "no-NO", "n ...

The code for implementing the "Read More" feature is not functioning as intended

I have been experiencing an issue with the implementation of the "read more" feature on my website. Although the code seems to be functioning properly, it only works after pressing the read more button twice. This particular code is designed to detect the ...

Prevent the border from shrinking upon being clicked

I'm currently working on customizing an accordion using jQuery for the animation effects. However, I am facing an issue where clicking on the accordion header causes the border around the plus sign to shrink in size as well. My goal is to only have th ...

Searching and Sorting through JSON Data in React Native

I am currently expanding my knowledge in React Native and experimenting with filtering a JSON data set on a screen. My goal is to display only the filtered results on the screen. Would it be advisable for me to create a new component called FilteredTicket? ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...