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

When using AJAX POST requests, HTML links may become unresponsive

Scenario: Currently, I am developing a small-scale web application. The AJAX functionality is successfully sending data to create.php which then executes the necessary MySQL query. Upon completion of the AJAX request, a success message is appended to the d ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

When an accordion is clicked, the content is dynamically loaded within the accordion on the page using PHP, jQuery, and AJAX

To optimize the loading speed of my information-filled page connected to two databases using php, javascript, jquery, I'm looking for a way to make the upload process faster. Currently, some data is displayed immediately while other details are hidden ...

What could be causing redux.props.reducer to return undefined?

I recently encountered an issue with my code. I have a function in the actions folder that successfully fetches a URL using axios. However, there seems to be a problem when trying to retrieve the data from the reducer. I have a mapStateToProps function set ...

JavaScript: Efficiently Replacing Multiple Text Instances

To ensure that users do not input multiple empty paragraphs in the text editor, I have found a method to eliminate a single <p><br></p> from the text within the editor message. var str = content.replace('<p><br></p> ...

Having issues with a local image not loading in React?

I am trying to display a local image in React js. After referring to this solution, I have tried the following code - <img src={require('../public/images/icon.png').default} /> The image "icon.png" is stored in my public folder, and I&apos ...

Converting coordinates of latitude and longitude into JSON format

I'm currently facing some challenges with organizing map waypoints, defined by latitude/longitude pairs, within a JSON array. This is the progress I've made so far. var llData = {}; var waypointData = {}; for (i = 0; i < routeArray.length; ...

Trouble Arising in Showing the "X" Symbol upon Initial Click in Tic-Tac-Toe Match

Description: I'm currently developing a tic-tac-toe game, and I've run into an interesting issue. When I click on any box for the first time, the "X" symbol doesn't show up. However, it works fine after the initial click. Problem Details: ...

Setting up secure HTTPS connections for Node.js and Vue.js

I am encountering an issue with my Laravel and Vue.js site, which also utilizes nodejs. Accessing the site via http works fine, but when attempting to use https, half of the site fails to load and I receive the following error in the console: Access to XML ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

"Utilize Selenium to navigate and select a menu option with a

In my dropdown menu, I am trying to use Selenium to move the mouse to the Documentation menu item and click on the App Configuration option within it. The mouse hover function is working properly, but I am unable to click on the App Configuration element. ...

I am interested in utilizing Vue Fallthrough attributes, but I specifically want them to be applied only to the input elements within the component and not on the container itself

I am facing an issue with my checkbox component. I want to utilize Fallthrough attributes to pass non-declared attributes to the input inside the checkbox component. However, when I add HTML attributes to the Vue component, those attributes are applied not ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Leveraging the power of Ajax and Nodejs to dynamically refresh content on a webpage

I'm currently working on creating a loop to refresh a webpage every 30 seconds, but I'm facing some challenges with making an ajax call using the setInterval function. Below is a snippet of my server-side code: var app = express() app.get(' ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Halt hovering effect after a set duration using CSS or Vanilla JavaScript

Looking for a way to create a hover effect that lasts for a specific duration before stopping. I want the background to appear for just 1 second, even if the mouse remains hovering. Preferably using CSS or JavaScript only, without jQuery. To see my curren ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

The Material UI Icon is missing from the location '@mui/icons-material/Send.js'

I am currently utilizing the Material UI library and attempting to import SendIcon through this import statement: import { SendIcon } from "@mui/icons-material/Send.js"; Due to including "type" : "module" in my package.json f ...