Error message encountered: JavaScript Firebase Realtime Database TypeError - Unable to use newChildren.insert function

I am having trouble with pushing, setting, and updating data on my Firebase Realtime Database. Below is the code I have been using. Any help would be greatly appreciated.

imports:

import { serverTimestamp, getDatabase, onChildAdded, push, set, update, runTransaction, get, ref as dbRef } from "firebase/database";
import { db } from "@/config/firebaseConfig";

In firebaseConfig, 'db' is simply a shorthand for getDatabase(app).

The set() function is throwing an error.

async sendMessage() {
   if (this.messageText.trim().length === 0) return;

    const chatRef = dbRef(db, `chats/${this.chatId}`);
    const snapshot = await get(chatRef);

    const newMessageRef = await push(chatRef);
    const newMessageKey = newMessageRef.key;
    
    const newMessage = {
        id: newMessageKey,
        sender: this.currentUser.uid,
        text: this.messageText.trim(),
        timestamp: serverTimestamp(),
    };

    console.log("newMessageRef:", newMessageRef);
    console.log("newMessage:", newMessage);

    await set(newMessageRef, newMessage);

An error has occurred:

caught (in promise) TypeError: newChildren.insert is not a function at IndexMap.ts:147:30 at map (obj.ts:50:21) at Proxy.addToIndexes (IndexMap.ts:115:24) at Proxy.updateImmediateChild (ChildrenNode.ts:156:38) at Proxy.updateChild (ChildrenNode.ts:180:19) at viewProcessorApplyUserOverwrite (ViewProcessor.ts:486:34) at viewProcessorApplyOperation (ViewProcessor.ts:103:22) at viewApplyOperation (View.ts:213:18) at syncPointApplyOperation (SyncPoint.ts:107:9) at syncTreeApplyOperationHelper_ (SyncTree.ts:726:9) (

I have tried using both the old and new API. The read and write rules are set to true in my database configuration.

Answer №1

The error message is pointing towards a potential issue with the data being passed to the set() method. It appears that the newMessageRef variable may not be correctly referencing a location in the Firebase Realtime Database.

One solution could be to use chatRef.child(newMessageKey) as the argument for set() instead of newMessageRef. By doing this, a new child node will be created under the chats/${this.chatId} location using the specified key.

async sendMessage() {
if (this.messageText.trim().length === 0) return;

const chatRef = dbRef(db, `chats/${this.chatId}`);
const snapshot = await get(chatRef);

const newMessageRef = push(chatRef);
const newMessageKey = newMessageRef.key;

const newMessage = {
    id: newMessageKey,
    sender: this.currentUser.uid,
    text: this.messageText.trim(),
    timestamp: serverTimestamp(),
};

console.log("newMessageRef:", newMessageRef);
console.log("newMessage:", newMessage);

await set(chatRef.child(newMessageKey), newMessage);

}

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

Instructions for creating a dynamic Google map based on an address

Specifics I am aiming to generate a map based on any address stored within my <span> The address in question is : 410 walker street Lowell MA 01851 The <span> containing the address reads as follows: Address: <span id="address" > 410 w ...

Can the ng-keypress listen for arrow key presses?

I'm looking to implement a functionality similar to the konami code "up, up, down, down, a, b, a, b, enter" -> triggering an action. Is it feasible to detect arrow key presses using ng-keypress in AngularJS? It doesn't seem to be working as e ...

Calculate the total height of all tables within the body element using Jquery

Is there a way to use jQuery to iterate through the content of the body element without using ids and determine the height of each table? Consider this HTML structure: <iframe id="A"> <html> <head></head> <body> ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

Relay information between requests using a RESTful API and various data formats, such as JSON, XML, HTML

In a scenario with a REST API that can deliver JSON, XML, HTML, and other formats, the default response for browsers without JavaScript enabled is HTML. This API utilizes tokens for authentication and authorization. Within a traditional website project, t ...

Tips for utilizing the data retrieved from a successful Ajax request

My goal is to extract a value from an Ajax success response and utilize it in another function; Below is the code snippet: Code: let requiredValue; $(function(callback){ $.ajax({ type:'GET', url: 'getfile.php', data:{ ' ...

What is the method for determining the active configuration?

I am working with a MongoDB database that consists of 3 collections. Each collection is exemplified below by a document: tag _id: ObjectId('61b873ec6d075801f7a97e18') name: 'TestTag' category: 'A' computer _id: ObjectId(&apo ...

What could be causing the issue of my ID not being retrieved from my PHP AJAX MYSQL URL?

Trying to extract the 'id' from the URL in order to load the page, but it's not displaying anything. Here is the URL: http://localhost/test/product.php?id=21 When I use: $product_query = "SELECT * FROM photo WHERE photo_id = '21&apos ...

Error with Firebase. Make sure the URL for your Firebase Realtime Database instance is set up correctly

Currently, I am utilizing the getServerSideProps function to retrieve data from my Firebase database for my Next.js application. This is how my code snippet appears: export async function getServerSideProps(context) { const session = await getSession( ...

What is the functionality of an asynchronous factory in AngularJS?

I've come across various responses to this query, but I'm still struggling to understand it. Where does the promise actually end up? I created a basic factory with an asynchronous call to a cloud database: app.factory('asyncFactory', f ...

The two divs are positioned on top of one another, with the link in the bottom div being unclickable

I am trying to create a unique effect where a tile divides into two on hover, with each tile acting as an individual link. Additionally, I want the background color of the tiles to change on hover. To achieve this, I have stacked two divs (toptile and bot ...

What is the procedure for refreshing a MySQL JSON column?

I am attempting to pass the following object as a parameter: {'0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE': '100000000000000000'} When trying to update a MySQL JSON column in this function, I encountered an error: ER_BAD_FIELD_ERR ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Register form using NodeJs with MongoDB database and Mongoose, integrating Express and passport

I've set up a signup form with fields for username, password, and email. I'm using MongoDB to store this data, and here's my schema: var mongoose = require("mongoose"); var Schema = mongoose.Schema; const passportLocalMongoose = require("pa ...

jQuery - simply tap or click on most areas to conceal a div and more

$(".clickPlan").click(function(){ $(".panel1").animate({left:'0px'}); }); $(".sendBtn").click(function(){ $(".panel1").animate({left:'300px'}); }); $(document).click(function() { $('.panelBox').fadeOut('fast&ap ...

persistent storage issue leading to vuex state not reflecting changes

I'm currently facing a puzzling issue regarding the lack of state change persistence in vuex. A snippet of the code causing me trouble is displayed below: <v-btn :disabled="!isEditing" color="success" @cl ...

How to Use a PHP Variable in an External JavaScript File

After going through multiple discussions on this platform, I am still facing challenges in passing a variable from PHP to an external JS file. Can anyone offer some help? This is what I have in my PHP file; <script type="text/javascript"> var pass_ ...

Tips for effectively directing JSON response to populate a table

I recently started learning ajax and I'm looking for some guidance. I'm currently working on fetching data through an API, and while I am able to see the response in the console, I'm struggling with targeting the specific data that I need to ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...

When using ReactJS, the modal body and footer may appear twice when loading data from an API

When trying to load data from a Laravel route using an Axios request in a modal, I am encountering the issue of the modal body and buttons showing twice inside the modal. Can anyone explain why this is happening? Below is the code snippet for reference. c ...