When an object is pushed into an array, it gets duplicated and also appears in a proxy when viewed in the console

Working with Firebase 9 and Vue 3 in building a chat application. The issue at hand is that when I push message objects to the messages array [], the console shows duplicates like this:

Proxy {0: {…}, 1: {…}}
  [[Handler]]: Object
  [[Target]]: Array(3)
    0: createdAt: ut {seconds: 1647944143, nanoseconds: 557000000}
    photoURL: "https://lh3.googleusercontent.com/a-/AOh14GjGXUIFOraxHTZqGIjTLkKGgyM8w7SvVDfF0XQ4=s96-c"
    sender: "Dif Az"
    text: "Test"
  [[Prototype]]: Object
    1: createdAt: ut {seconds: 1647944149, nanoseconds: 756000000}
       photoURL: "https://lh3.googleusercontent.com/a-/AOh14GjGXUIFOraxHTZqGIjTLkKGgyM8w7SvVDfF0XQ4=s96-c"
       sender: "Dif Az"
       text: "Halo"
  [[Prototype]]: Object
    2: createdAt: ut {seconds: 1647944143, nanoseconds: 557000000}
       photoURL: "https://lh3.googleusercontent.com/a-/AOh14GjGXUIFOraxHTZqGIjTLkKGgyM8w7SvVDfF0XQ4=s96-c"
       sender: "Dif Az"
       text: "Test"
  [[Prototype]]: Object
  length: 3
  [[Prototype]]: Array(0)
  [[IsRevoked]]: false

Upon submitting new messages in the console, the array continues to duplicate as seen above with new values repeating.

Chat.vue?0d25:56 Proxy {0: {…}, 1: {…}, 2: {…}}

Answer №1

Each time the onSnapshot listener is triggered, it receives a QuerySnapshot that contains all the data from the messageRef. This means that on subsequent calls, the full data is received again, not just the changes.

To handle this, you can either work with snapshot.docChanges, which only includes the modifications, or (a simpler approach) clear the this.messages array when the function is called again.

Here's an example of how to achieve this:

onSnapshot(messageRef, (snapshot) => {
  this.messages = snapshot.docs.map((doc) => doc.data().messageInfo);
})

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

Is it possible to include numbers and commas in JQuery Validation?

I have implemented a jQuery validation plugin to validate the fields of a form. One specific requirement is to validate a field to only allow commas and numbers. Below is the HTML code snippet: <input type="text" placeholder="Number of Employees" requ ...

Leverage child component methods in parent component using Vue.js with CDN assets

Recently, I made the switch from Alpine.js to Vue.js (CDN) in order to experiment with async functions. My objective is to call a method from the parent component that is defined within a child component. However, when attempting to call "test()" ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

Setting state in a functional component is not possible when data is being fetched from Firebase in a ReactJS application

useEffect(() => { console.log("mounted"); all.db.ref("NewDonor").on("child_added", (data) => { var DataFromDB = data.val(); state.donor.push(DataFromDB); console.log(state.donor); setState({ donor: DataFromDB ...

Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models: public class CourseVm { p ...

Unique: "Unique One-Step Deviation in Date Comparison"

A Little Background Information: I am working with data points that span from the current day to 5 days ahead, in 3-hour intervals (such as 10pm, 1am, 4am, 7am...). My goal is to organize these data points into arrays sorted by date, with each array repre ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

The JQuery functionality is failing to execute properly on Internet Explorer

I have developed a JQuery script that appears to be working perfectly in all browsers, except for IE 8. Interestingly, when I checked Internet Explorer's error details, it did not provide any specific information about the issue. Instead, IE simply po ...

How can I use Node.js Express to send a response in a file format like JavaScript or another type?

Currently, I have a piece of code that successfully reads the 'example.js' file and sends it to the client as requested. app.get('/mods/example.js', function(req, res) { fs.readFile('./mods/example.js', {encod ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Struggling to comprehend the filtering arguments in VueJS?

While going through the VueJS Filter(orderby) API documentation, I came across some confusion regarding the arguments. Below is a sample for reference: Arguments: {String | Function} targetStringOrFunction "in" (optional delimiter) {String} [...s ...

What is the best way to incorporate a generated ID into the datepicker() function whenever a button is clicked?

I'm looking to dynamically generate a row of input fields with unique IDs every time the "add another flight" button is clicked, similar to the functionality seen on destina.us. Additionally, I need to incorporate these generated IDs into the jQuery U ...

Add a sub-modal window inside a separate container

Is there a way to attach this modal to an external div? The current setup involves nesting it within a container that has a fixed height. I'm looking to move it outside of that container. Here is the JavaScript code for the modal: client.fetchQuery ...

What is the method for entering a value in Code Mirror using Selenium WebDriver?

Struggling with inserting input values into Code Mirror, which is HTML code. Any assistance would be greatly appreciated! This is what I have been attempting so far (but I need to insert values on each line of Code Mirror) JavascriptExecutor js = (Javas ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

Adding an event listener to detect left or right mouse clicks - using onclick doesn't capture right clicks

I'm currently in the process of applying for an Internship through this Internship Link One thing that caught my attention right away is the issue with uploading or pasting a cover letter. When attempting to upload or paste a cover letter, it redirec ...

Retrieve the list of device tokens for the APNS service

Is it possible to retrieve a list of all device tokens on which my app is installed through an APNS endpoint? I am aware of the feedback service that provides the status of devices to whom messages are sent, but I believe this is only after the message ...

Encountering an issue when using both the Google Maps API and Google URL Shortener API within the same program

Recently, I developed a program that involves passing data to an iframe through a URL. However, due to the limitation of Internet Explorer supporting only 2083 characters in a URL, I decided to use the Google URL Shorten API to shorten the URL before sendi ...