Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it.

Below is my Controller:

public function addComment() 
{
    $this->validate(request(), [
        'comment' => 'required',
    ]);

    $comment = [
        'comment' => request()->comment,
        'article_id' => request()->article_id,
        'user_cid' => Auth::user()->user_cid,
    ];
    $comment = ArticleComment::create($comment);
    return new ArticleCommentResource($comment);
}

And here's my Vue.js method:

data() {
        return {
            data: [],
            comments:[],
            form: new Form({
                comment: '',
                article_id: this.articleid,
            })
        }
    },  
methods: {
        onSubmit() {
            this.showLoader = true
            this.form.post('add-comment')
                .then(response => {
                    console.log(response.article_id);
                    this.form.article_id = response.article_id;
                });

        },
 }

If anyone has any insights on how to approach this issue, I'd be very grateful for the help. Thank you!

Any assistance would be much appreciated. Thanks in advance.

Answer №1

In order to update your list by adding a new comment at the top, you should insert the response data at the beginning of the comments array:

submitComment() {
    this.showLoader = true
    this.commentForm.post('add-comment')
        .then(response => {
            this.comments.unshift(response);
        });
},

This method assumes that the response contains the new comment information (without knowing the details of your specific commentForm implementation).

Answer №2

<script>
    import FormData from 'form-validation-helper';

  export default {
      data:() => ({
         formData: new FormData({
              post_id: null,
          }),        
      }),

      mounted() {
        this.loadData();  
      },

      methods: {
          async loadData() {
              const dataResponse = await this.formData.sendPostRequest('add-post');
              this.formData.post_id = dataResponse.post.id; 
          }
      }
  }
</script>

Give this a try.

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

A TypeError is thrown when attempting to use window[functionName] as a function

I came across this page discussing how to call a function from a string. The page suggests using window[functionName](params) for better performance, and provides an example: var strFun = "someFunction"; var strParam = "this is the parameter"; //Creating ...

Issues with implementing Bootstrap tabs in Vue application

Currently, I am in the process of developing an application using vue, vue-router, and bootstrap. My goal is to integrate tags in bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-l ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

Tips for personalizing the file names generated by Vue CLI?

Struggling to locate instructions for reducing assets and generating *.min.js files with vue cli. Currently running vue cli version 4.2.3. The file extension must be *.min.js for rollbar to work properly. Any suggestions on setting up vue cli to generate ...

How can we efficiently iterate through an array in Node.js while making asynchronous calls?

I need to iterate through an array, pushing a new Thing to a list in the process. The Thing itself performs asynchronous calls. However, I am facing an issue where my for loop is synchronous but the new Things are asynchronous, causing the callback to be c ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

Converting Geometry into BufferGeometry

From my understanding, Geometry contains a javascript object structure of the vertices and faces, while BufferGeometry stores raw WebGL data using Float32Arrays, etc. Is there a method to convert regular Geometry into BufferGeometry, which is more memory ...

What is the best way to incorporate a sidebar menu in an HTML webpage?

I am interested in creating a sidebar menu for my website using either HTML, CSS, or JavaScript. The W3 Schools website has a side menu that I find appealing and would like to create something similar. ...

Is there a way for me to replace zero with a different number dynamically?

Is there a way to dynamically insert a different number instead of zero in mongoose? displayCity: (req, res, next) => { let id = req.params.id; provinceAndCity.findById({ _id: id }).populate('city.0.limitation', 'title ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

When using Angular $http.post, encountering issues with the 'Access-Control-Allow-Origin' header

I have developed two applications using nodejs and angularjs. The nodejs app contains the following code: require('http').createServer(function(req, res) { req.setEncoding('utf8'); var body = ''; var result = '&a ...

Utilizing conditional statements and time to dynamically alter the class of an object

I need to change the class of an object based on the time, with two classes available: recommendedspot and notrecommended. The code I've written so far is not displaying the image correctly. Can someone help me troubleshoot this issue? Here is my cur ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

how to toggle a pre-selected checkbox in a Vue component

https://i.stack.imgur.com/6GQl7.png When dealing with a tree view checkbox in Vue, I encountered an issue where editing data within a selected zone should automatically check the corresponding countries based on previous selections. The ID of the selected ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

Issues with Angular 8 arise when attempting to use JavaScript after pressing the back button in the browser

While working on my Angular 8 project, everything runs smoothly until I hit the browser's back button. Once I do this, my external JavaScript stops functioning. I have tried using JavaScript in various ways, such as importing, requiring, and putting ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...