Learn the process of appending an item to a list using Vue.js

Recently starting with vue.js and facing an issue:

data: {
        ws: null, 
        newMsg: '',
        username: null,    
        usersList: '' 
    },
        created: function() {
        var self = this;
        this.ws = new WebSocket('ws://' + window.location.host + '/room');
        this.ws.addEventListener('message', function(e) {
            var msg = JSON.parse(e.data);
                if (msg.Message == "joined" ) {
                self.usersList.push(msg.Name); // <--Issue persists here 
              }


        });
    },

However, encountering an error displayed in the browser console:

Uncaught TypeError: self.usersList.push is not a function

Even after trying to use a static string instead of msg.Name, the error remains the same.

What could be the problem here and how can it be resolved?

Answer №1

1. Utilize the userList:[] as an array and employ the push() method. For further information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

2. If the content of e.data is in array format, such as [1,2,3,4], you can utilize the concat method to merge two arrays.

var arr1 = [1,2,3,4];
var arr2 = [5,6,7];
var arr = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6, 7]

Alternatively, you can use

Array.prototype.push.apply(arr1, arr2);
to add all elements from a second array.

var arr1 = [1,2,3,4];
var arr2 = [5,6,7];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);//[1, 2, 3, 4, 5, 6, 7]

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

Error: Trying to destructure a non-iterable object with useContext in React is not valid

ERROR [TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.] Using UserContext : import React, { useContext, useEffect, useLayoutEffect, useState } from "reac ...

The parameter passed to the parser as an argument of [object Object] was found to be an invalid GraphQL DocumentNode. It is recommended to utilize 'graphql-tag' or an alternative approach to properly convert the parameter

Whenever I attempt to utilize useQuery from @apollo/client, the following error crops up: "Invariant Violation: Argument of [object Object] passed to parser was not a valid GraphQL DocumentNode. You may need to use 'graphql-tag' or another ...

Is there a way for me to prevent the setTimeout function from executing?

I have a function that checks the status of a JSON file every 8 seconds using setTimeout. Once the status changes to 'success', I want to stop calling the function. Can someone please help me figure out how to do this? I think it involves clearTi ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Error: Unable to access attachShadow property as it is null and cannot be read

Having an issue with my vue component where I am getting a TypeError: Cannot read properties of null (reading 'attachShadow') error when building it as a web component. Here is the command I am using to build the vue component: vue-cli-service bu ...

Show a success message once the jQuery Ajax operation is successful and then refresh the page

I am looking to implement a feature where a Bootstrap alert message is shown immediately following a successful AJAX request and page refresh. success: function(res) { window.location.reload(); $('#success').html('<div class=&qu ...

Challenges encountered when trying to showcase API data in Angular 6

In my application, I am making a call to the iTunes API and when I check the response, it is showing as [object object]. I believe this might have to do with the way the API's array structure is set up. I have a service injected into a component setup ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Unlocking the intricacies of navigating through nested arrays of objects in JavaScript

I need help figuring out how to loop through a nested array of objects in my code. I've tried different approaches but can't seem to grasp how it works. The object data I have looks like this: [ { "restaurantName":"Bron ...

javascript onload select the text in the textarea

Is there a way to have JavaScript automatically highlight the text inside a textarea when the page is loaded? ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

What is the best way to access the Vue instance within Vite?

Just diving into Vue 3 and Vite. How can I access the Vue instance? In the past, I would usually... import Vue from 'vue' However, in my Vue3/Vite project, there is no default export in the vue module, so when I try... Uncaught SyntaxError: The ...

Updating a PlaneBufferGeometry in Three.js - Tips and Tricks

I'm currently working on implementing an ocean effect in my Three.js project. I found a helpful example on this website: https://codepen.io/RemiRuc/pen/gJMwOe?fbclid=IwAR2caTQL-AOPE2Gv6x4rzSWBrOmAh2j-raqesOO0XbYQAuSG37imbMszSis var params = { res : ...

Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them. In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding p ...

Tips for resolving syntax errors in try-catch blocks when working with Node.js

I have encountered an issue with the code in my controller.js file. It runs fine on my local machine, but when running on an AWS EC2 instance, I am getting an error. Can someone help me with this problem? query(request_body,(results,error) =>{ if ...

Comparing the Impact of Queries and Filters on Performance in MongoDB and Node.js

There are two methods I am using to calculate the count of documents based on their status. Here are the two methods: collection.find({ Status: 'pending' }).count(function (e, pending) { collection.find({ Status: 'open' }).count(functi ...

Bringing to life in Vue.js

I am a beginner with Vue.js and I have been attempting to integrate Materialize into my project. I have experimented with various plugins such as vue-materialize (https://github.com/paulpflug/vue-materialize) and vue-material-components (https://www.npmjs. ...

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...