Error in Vue.js when attempting to push using the sendMessage method

I am facing an issue with the following method:

 props: ['convId'],
  data() {
        return {
            messages: [],
            newMessage: ''
        };
 },

 methods: {
        sendMessage() {
            axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
                    .then(response =>  this.messages.push(response.data.data));

            this.messages.push(newMessage);

            this.newMessage = '';

            console.log(this.messages.id); //TypeError: Cannot read property 'id' of undefined
        }
  },

After trying to retrieve the updated this.messages object, I encountered undefined properties. Why is this happening?

The response from the request includes the following object:

{"body":"test","user_id":1,"type":"text","conversation_id":1,"updated_at":"2018-06-04 13:15:27","created_at":"2018-06-04 13:15:27","id":16,"conversation":{"id":1,"private":1,"data":null,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-04 13:15:27","users":[{"id":1,"name":"Axer","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="770312040337101a161e1b5914181a">[email protected]</a>","created_at":"2018-06-01 12:35:37","updated_at":"2018-06-01 12:35:37","pivot":{"conversation_id":1,"user_id":1,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}},{"id":2,"name":"Testumus","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196d7c787d786a7d786a7d597e74787075377a7674">[email protected]</a>","created_at":"2018-06-01 12:46:30","updated_at":"2018-06-01 12:46:30","pivot":{"conversation_id":1,"user_id":2,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}}]}}

What steps can I take to resolve this issue?

Answer №1

Ensure that you have set the newMessage variable correctly. Perhaps you intended to use this.newMessage.

If you want to retrieve the inserted result, consider returning the database data in the response and then adding the message. This way, you can access the id and other columns needed for logging on the console.

 axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
       .then((response) {  
             this.messages.push(response.data.data) // Received message from server
             this.newMessage = '';
             console.log(this.messages.id); 
  })

Answer №2

         props: ['convId'],
          data() {
                return {
                    messages: [],
                    newMessage: ''
                };
         },

         methods: {
                sendMessage() {
                    axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
                            .then((response) {  
                                  this.messages.push(response.data.data);
                                  this.messages.push(newMessage);
                                  this.newMessage = '';
                                  console.log(this.messages.id); 
                             });
                }
          },

Give it a shot.

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

What could be causing issues with my setup for submitting forms in Django and using jQuery AJAX?

Although I have encountered questions like this numerous times before, I am struggling to make my AJAX form function correctly using jQuery on the client side and Django on the server side. Despite researching extensively, I have not come across a step-by- ...

Having difficulty drawing an arrow connecting one mesh object to the surface of another mesh object

When attempting to draw an arrow from one mesh object to another, I encountered some issues. Directly using the positions of the objects as arguments in the Arrow Helper resulted in the arrow going inside the object due to the position representing the cen ...

Troubleshooting a "Cannot GET" error while using Vue.js with a REST API

I am currently working on a project with Vue.js and I am running it locally through npm (Node). As a newcomer to Rest APIs, I followed an online tutorial to create a simple REST API. The file is named employees.php <?php // Establish database connect ...

Insert a new HTML element only if it is not already present

<p id="main_class"> <span class="new_class"></span> </p> In this code snippet, I am attempting to append <span class="new_class"></span> to the element with the id of main_class. If the span element with the class o ...

Configure parameters for Shopware navigation path

When initializing my Shopware 6 plugin, I encountered an issue with the Vue Router not recognizing a standard ID on the first page. routes: { list: { path: 'list/:id', component: 'plugin-list' }, ...

Display the current position of the caret in a field that cannot be edited

Can a virtual caret be displayed between two letter boundaries in HTML/CSS/JavaScript, for example in a regular div without using contenteditable=true? Imagine having the following: <div>Hello world</div> If I were to click between the "w" a ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

What could be the reason for the mismatch in size between the downloaded file in Express.js and the file size on the server?

My code using express.js is quite simple: app.get("/download", download); and export let download = async (req: Request, res: Response) => { const file = "/tmp/my-file.zip"; res.download(file); } The client-side code is also straightforward: im ...

Building a class structure with a JavaScript MVC approach - best practices

I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other com ...

Unable to alter the background color in a table row when a condition is verified

Within my 'work' array that is generated from an Excel file, I have values for employee_id (referred to as id), projects, and hours. Additionally, I have another array called 'employees' which contains all the employees in my database. ...

What could be causing csg.js to malfunction with boolean operations in Three.js?

Just starting out with three.js and csg.js. I've set up a basic scene like this: // Setting up the scene const scene = new THREE.Scene(); // Adding a perspective camera - defining FOV, aspect ratio, near and far clipping plane const camera = new THREE ...

Creating a customized function in javascript/jquery with the ability to override it

Currently, I am utilizing Visual Studio for writing JavaScript/jQuery. For instance, when I input: $('#selector').text('foo') and then highlight text and hit F12, Visual Studio directs me to the file jquery-2.2.3.intellisense.js, auto ...

Reorder an array of objects in JavaScript alphabetically, taking into account any possible null values

Encountering a problem with sorting contacts by first name, especially when some contacts are missing this information. Any suggestions on how to modify the method for such cases? Thanks! This is the current sorting function I am using: function sortAZ(o ...

Concealing rows with empty cells in column E

As someone who is fairly new to incorporating scripts in Google Sheets, I stumbled upon this straightforward and beneficial code snippet online. My objective is to conceal rows within a specified range (rows 10 - 34) where there are blank cells in column E ...

Arrangement of JavaScript objects based on timestamp key

In JavaScript, there are specific rules that dictate the order of object properties. One interesting example caught my attention. When a timestamp in milliseconds is used as an object property key, the ordering does not function as expected. However, if ...

Utilize a function with Document Write to output content onto a textarea

I am trying to implement a function that will display the result in a textarea using Javascript. Currently, the function writes the output on the body using document.write. However, I want the function to be triggered by an onclick button and display the ...

From time to time, I may post files of substantial size

When moving to the next step in the form, I have implemented checks to prevent photos over 10mb and disallow .heic files from being uploaded. Most of the time it works as expected, but occasionally files slip through. If anyone has suggestions for a more ...

Instructions for bringing the v-overlay element into view as soon as the page loads

Currently, I am in the process of developing an application using Nuxt v3.9.3 and Vuetify 3.5.1. I have incorporated the "absolute" link below into my implementation, which displays an overlay when a button is clicked. <template> ... <div id=&qu ...

Concealing jQueryUI tooltip upon clicking a "target=_blank" link

I have implemented jQuery to display tooltips for all links on my webpage that include a 'details' attribute. $(function() { $tooltip = $(document).tooltip({ show: false, track: true, ...

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...