There was an issue with the v-on handler that threw an error: "Error: Reference.set failed because the first argument contains undefined."

I'm struggling to pinpoint where exactly the error occurs. Despite numerous attempts to log all the input data for the database, everything seems to have values...

https://i.sstatic.net/TBk1L.png

The goal is to store the current message in the database for a real-time chat application. Below is the code snippet.

This project uses Firebase and VueJs.

CreateMessage.vue (potential error location)

<template>
    <div class="container" style="margin-bottom: 30px">
        <form>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Enter message ..." v-model="newMessage">
                <p class="text-danger" v-if="errorText">{{ errorText }}</p>
            </div>

            <button class="btn btn-primary" type="submit"  @click.stop.prevent="createMessage"> Submit</button>
        </form>
    </div>
</template>

<script>
    import firebase from '../components/firebaseconfig';
    import AuthMonitor from '../AuthMonitor';
    import Login from '../components/Login';

    export default {
        name: 'CreateMessage',
        mixins:[AuthMonitor],
        data(){
            return {
                newMessage: "",
                errorText: "",
                user: firebase.auth().currentUser
            }
        },
        methods: {
            createMessage () {
                console.log(this.newMessage);
                if (this.newMessage != '') {
                    console.log(Date.now());
                    firebase.database().ref("messages").push().set({
                        message: this.newMessage,
                        name: this.user,
                        timestamp: Date.now()
                }).catch(err => {
                        console.log(err);
                    });
                this.newMessage = "";
                this.errorText = "";
                } else {
                    this.errorText = "A message must be entered!"
                }
            }
        }
    }
</script>

ChatRoom.vue . (the view)

<template>
    <div class="chat container" v-if="isAuth">
        <h2 class="text-primary text-center">Real-Time Chat</h2>
        <h5 class="text-secondary text-center">Powered by Vue.js & Firebase</h5>
        <div class="card">
            <div class="card-body">
                <p class="nomessages text-secondary" v-if="messages.length == 0">
                    [No messages yet!]
                </p>
                <div class="messages" v-chat-scroll="{always: false, smooth: true}">
                    <div v-for="message in messages" :key="message.id">
                        <span class="text-info">[{{ message.name }}]: </span>
                        <span>{{message.message}}</span>
                        <span class="text-secondary time">{{message.timestamp}}</span>
                    </div>
                </div>
            </div>
            <div class="card-action">
                <CreateMessage/>
            </div>
        </div>
    </div>
</template>

<script>
    import CreateMessage from '@/components/CreateMessage';
    import firebase from '../components/firebaseconfig';
    import AuthMonitor from '../AuthMonitor';
    import moment from 'moment';

    export default {
        name: 'Chat',
        mixins:[AuthMonitor],
        components: {
            CreateMessage
        },
        data() {
            return{
                messages: []
            }
        },
        // created() {
        //     let ref = firebase.database().ref('messages');

        //     ref.onSnapshot(snapshot => {
        //         snapshot.docChanges().forEach(change => {
        //             if (change.type == 'added') {
        //                 let doc = change.doc;
        //                 this.messages.push({
        //                     id: doc.id,
        //                     name: doc.data().name,
        //                     message: doc.data().message,
        //                     timestamp: moment(doc.data().timestamp).format('LTS')
        //                 });
        //             }
        //         });
        //     });
        // }
    }
</script>

<style>
.chat h2{
    font-size: 2.6em;
    margin-bottom: 0px;
}

.chat h5{
    margin-top: 0px;
    margin-bottom: 40px;
}

.chat span{
    font-size: 1.2em;
}

.chat .time{
    display: block;
    font-size: 0.7em;
}

.messages{
    max-height: 300px;
    overflow: auto;
}
</style>

Answer №1

When you see the error message, it means that the variable this.user has a property ja with an undefined value. Storing undefined values in Realtime Database is not allowed.

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

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

Error possible in modal due to interaction between JavaScript, PHP, and Bootstrap - Unable for PHP file to successfully retrieve value from JavaScript file

I have an existing database that is already populated. Additionally, I have a JavaScript function that captures the ID of the element when a button is pressed. Here's an example: Name of Subject | Actions -------------------------------------- ...

Tips for choosing and emphasizing specific lines in a dxf document with the help of three.js, dxf-parser, and three-dxf

Incorporating both the dxf-parser and three-dxf libraries, I am working on a webpage to display dxf drawings with the help of the three.js library. Although I was successful in loading the dxf file onto the webpage, I encountered difficulties in highligh ...

Passing arrays from child to parent components in VueJS: A comprehensive guide

I am currently utilizing the Vue-Multiselect plugin and attempting to send data up to a parent component so that a backend API can update certain records. However, I am facing challenges in achieving this successfully. My approach (explained in detail) al ...

What is the process for transforming a plain JavaScript array into a hierarchical graph format?

Is there a way to transform this flat json construct: [ ["a","b","c"], ["a","b","d"], ["c","b","e"], ["c","b","f"] ] Into the specified graph structure utilizing javascript? {"uri": "a", "subItems": [ {"uri": "b", "subItems": [ ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

Change the value PRIOR to executing a function with ajax included

When the page loads, the following code triggers an API request and returns the result. Afterwards, there is code that updates one of the variables when a selector is changed, and then makes the API request again using the newsFeed() function. However, I& ...

Display an image in Vue.js

I'm having some trouble displaying images in my laravel/Vue 2.0 project and could use some assistance. Here's how I upload the image using the Laravel controller: //Save image to disk if($request->hasFile('image')) { ...

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Should I initiate a new dispatch or is there another reason why my code isn't executing?

I'm currently working on implementing a functionality where my preload shows up during an AJAX request and disappears once the request is completed, regardless of success or failure. Utilizing Axios, I've explored their interceptors for managing ...

Having issues with JavaScript/jQuery onclick functionality

My attempts to test a script using the test.html document are failing. I can't figure out why nothing is happening. The Script is contained within script tags and wrapped with style tags. Why isn't it working? Here is the code <!DOCTYPE html& ...

Unlocking the Power of Javascript Promises in FileReader

I am facing an issue with my code. Here is the HTML snippet: <input type='file' multiple> And this is my JavaScript code: var inputFiles = document.getElementsByTagName("input")[0]; inputFiles.onchange = function(){ var fr = new File ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

After replacing content with replaceWith in jQuery, the load event can

Currently, my goal is to use AJAX to load new content and replace the existing content on the page with this newly downloaded information. However, I am facing an issue in binding the load(handler(eventObject)) event for the replaced data. My requirement i ...

Next-auth encounters a TypeError [ERR_INVALID_URL] when attempting to use an invalid URL exclusively in the production

When I attempt to sign in using next-auth in my Next.js app in production mode by running the command `yarn build && yarn start` on my local machine, the app fails. The error message displayed in the terminal is: TypeError [ERR_INVALID_URL]: Invalid URL ...

VueJS is unable to access the requested resource due to the absence of an 'Access-Control-Allow-Origin' header

Currently, I am working on a VueJS application that requires calling an external API. The code snippet below demonstrates my approach: this.$http.get(myAPIurl) .then(response => { return response.json(); ...

Tips for creating a smooth transition between background colors within a div

Is there a way to smoothly transition between background colors within a div element? I've been struggling with my code and couldn't find a solution. Any help would be greatly appreciated. Thanks in advance. $(document).ready(function( ...

Navigating between pages in a multi-page setup using vue.js: A comprehensive guide

I came across a helpful post at this link about implementing multiple pages in Vue.js CLI. After setting up multiple pages, I was excited to test it out. However, I encountered an issue when trying to access the different pages from the URL http://localho ...

When using Nativescript Vue on Android, the keyboard may cover the TextView or Actionbar components

When I open the keyboard in a NativeScript Vue chat app, the page content overlaps with the ActionBar. Then, if I close and reopen the app, the keyboard input covers the TextView component. I expected the behavior to be similar to "Fb Messenger chat": the ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...