Struggling to add data to an array within a child component in vue.js resulting in an error: "Unable to access property 'push' of undefined."

My child component is displayed below:

<b-container fluid class="bv-example-row">
        <b-row>
            <b-col cols="2" class="col-speaker">
                <b-row>
                    <b-input-group @keyup.enter="speakerInput" class="input-speaker">
                        <b-form-input  v-model="speaker" placeholder="speaker"></b-form-input>
                    </b-input-group>
                    {{speaker}}
                    <div class="w-100"></div>
                    <b-col>
                        <img class="caption-flag" src="../assets/flag (2).png">
                    </b-col>
                </b-row>
            </b-col>
            <b-col>
                <div class="mainDashboard-caption">

                <h4 class="caption-timecode">{{start}}-{{end}}</h4>
                <b-row>
                    <b-col cols="11">
                        <b-form-textarea id="textarea1"
                                        v-model="userInput"
                                        placeholder="Enter something"
                                        :rows="3"
                                        :max-rows="6">
                        </b-form-textarea> 
                    </b-col>
                    <b-col>
                        <input class="caption-reviewed" type="checkbox"> 
                    </b-col>
                </b-row>

                <b-row class="row-buttons">
                    <b-col class="col-buttons">
                        <b-button :pressed="false" variant="outline-success" class="caption-merge-next">merge next</b-button>
                        <b-button :pressed="false" variant="outline-danger" class="caption-merge-prev">merge prev </b-button>
                    </b-col>
                </b-row>
                </div>
            </b-col>
        </b-row>
    </b-container>
</template>

<script>
export default {
    name: 'MainDashboard',
    props: {
        start: { type: Number, required: true},
        end: { type: Number, required: true},
        text: '',
    },

    data () {
        return {
            userInput: '',
            speaker: '',
            plainText: false,
        }
    },

    methods: {
        speakerInput (speaker) {
        console.log(speaker)
            this.$emit('post-speaker', speaker)

        }

    }



}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

The parent component is displayed below:

<template>
    <div class="dashboardView">
        <div class="header">
            <MainHeader
            v-bind:fileName= this.fileName
            />
        </div>
        <div class="dashboard" v-for='caption in captions' :key='caption.end'>
            <MainDashboard 
            v-bind:start='caption.start'
            v-bind:end='caption.end' 
            v-bind:text='caption.text'

            @post-speaker="postSpeaker"                       
            />
        </div>
        <div class="footer">

        </div>
    </div>
</template>

<script>
// @ is an alias to /src
import axios from 'axios'

import MainHeader from '../components/MainHeader.vue';
import MainDashboard from '../components/MainDashboard.vue';

export default { 
  name: 'dashboard',
  components: {
      MainDashboard,
  },
  data () {
    return {
      speakers: [],
      speaker:'',
      captions: [],
      text: '',
      fileName: '',
      result: this.getCookie('csrftoken')

    }

  },
  methods: {

    getCookie(key) {
      const regexp = new RegExp(`.*${key}=([^;]*)`);
      const result = regexp.exec(document.cookie);
      if(result) {
        return result [1]
      }
    },
    postSpeaker(speaker) {
      console.log(speaker)
      this.speakers.push(speaker)
      console.log(this.speakers)
      this.getCookie('csrftoken')
      axios.put('https://172.28.128.13/api/transcriptions/1/',{
          captions: {
            speakers: [this.speakers], captions: [this.captions]
          }
      },
       { 
         headers: {
            'X-CSRFToken': this.result} 
        }) 
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    },
  },

  created() {
    axios.get(`https://172.28.128.13/api/transcriptions/?format=json`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.captions = response.data.results[0].captions
      this.fileName = response.data.results[0].media_file
      this.speakers = response.data.results[0].captions.speakers
      console.log(this.fileName)
      console.log(this.captions)
    })
    .catch(e => {
      this.errors.push(e)
    })
  },
  components: {
    MainHeader,
    MainDashboard,
  },
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

I am attempting to emit the user's input data from the child component to the parent component and then push it into the speakers array. However, I encounter an error on this.speakers.push(speaker) in the parent component which results in the following error:

[Vue warn]: Error in event handler for "post-speaker": "TypeError: Cannot read property 'push' of undefined"

I believe there may be a small mistake that I'm making, and any assistance would be greatly appreciated :)

Answer №1

The issue lies within the child component:

@keyup.enter="speakerInput"

If you take a closer look, speakerInput requires the parameter speaker in order to emit the event to the parent.

To fix this, modify it to:

@keyup.enter="speakerInput(speaker)"

Alternatively, you can update speakerInput method to directly access the data instead of relying on it being passed:

methods: {
    speakerInput () {
        console.log(this.speaker)
        this.$emit('post-speaker', this.speaker)
    }
}

I hope this explanation clarifies things for you!

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

The decoding of my JSON data in PHP is not working as expected

My AJAX is sending JSON data to my PHP script, but I'm encountering an issue with decoding it. This is the jQuery code: $.ajax({ url : 'admin/modifyPermissions', type : 'post', data : { 'JSON' : JSON ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Is it possible to design login and register pages in ReactJS + Redux without the need to integrate with a backend system?

I am in the process of building a login and register page with ReactJS + Redux. After a user registers, their information is stored in an array like so: const userDataReducer = function(users = [], action){ switch (action.type){ case 'ADD_USER ...

Enhancing connections in a MongoDB database

Can someone assist me with implementing the update function in the assignmentsController? I want users to create an assignment and then be able to add a quiz to it. After updating the assignment quiz section, here is an example of what I expect as a return ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

Ways to dynamically update the source of a ReactJS video player

I'm having trouble dynamically changing the background video source based on the current state value in my functional component. Even though I've set up a conditional statement where {weather.weather} state is 'clouds' should display th ...

Prevent specific fields from being saved in Node MongoDB native

When working with MongoDB and using the node mongodb native driver to insert documents, I have encountered an issue. The objects I am inserting have fields that I do not want to be saved in the database: var x = { field: 'value', _nonPersist ...

Is it better to set the height of Material UI CardMedia based on aspect ratio or use vh

const customStyles = createStyles({ media: { height: 183 } }); <CardMedia className={classes.media} image="pic.jpg" /> Instead of setting the size in pixels, is there a method to adjust it based on an aspect ratio? For instanc ...

How can I effectively design a vertical table with a split background for optimal visual appeal?

Is there a way to creatively present this data with a split background using html and css? https://i.sstatic.net/qsCOM.png ...

Equally distributing the space while adjusting the size of the browser window

When adjusting the size of the browser window, I noticed that the space after the element is reduced. I would like to decrease the space equally on both the left and right sides, similar to how it is done on Facebook. Below is the code I have: CSS: body ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Ending the iteration in a TypeScript/JavaScript function by utilizing a for loop within

Currently, I am facing a challenge in breaking an iterative loop and returning false when a specific condition is met. Essentially, my goal is to determine whether a reactive form is empty or not: public isEmpty(form: AbstractControl): boolean { if ...

Continuously receiving the "Add to home screen" prompt despite already installing the PWA app

Is there a method to determine if the Progressive Web App has already been installed? It is possible to cancel the prompt event in the 'beforeinstallprompt' event. window.addEventListener('beforeinstallprompt', (event) => { // co ...

How to obtain the full path of a file downloaded using a Chrome extension

Currently in the process of creating a chrome extension that has the functionality to download specific files from various webpages. For this purpose, I have designed a popup.html where users can input the desired name for the file to be downloaded. Additi ...

Add all elements except for the last one

<div id="container"> <div class="sub">a</div> <span id="add">add</span> </div> $('#add').click(function(){ $('#container').append('<div class="sub">a</div>&ap ...

Retrieve information from two separate HTTP requests and merge them together

Two mongoose schemas are used in my project - one for storing information about doctors and another for ranking them. Here is the schema for doctors: var doctorsSchema = new schema({ Entity: {type:String}, name: {type:String}, Expertise : {type:Stri ...

What is the best way to handle mapping an array with uncertain levels of nesting?

My task involves rendering an array of comments in ReactJs, each of which can have nested comments at unknown levels. I am struggling to figure out how to display these comments with their respective nesting levels. comment 1 -- comment 2 -- comment 3 --- ...

Refresh the Morris chart using jQuery after a .NET MVC post request

In my .NET Controller action, I have written code to fetch specific time zone and group data based on that time zone. The code looks like this: [HttpPost] [ActionName("FetchTimeZone")] public ActionResult FetchTimeZone(string timeZone) ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

Issue with Jquery AJAX success function specifically in Firefox browser, while other functions in the script are functioning correctly

I have 4 scripts using ajax, but one of them isn't functioning properly in Firefox. Even the alert in success doesn't trigger anything. There are no error messages, just nothing happening. However, it works perfectly fine in IE and Chrome. Belo ...