Challenges with communication between parent and children components in 'Vue.js'

My application is designed to make multiple requests and display the resulting data. Everything is functioning properly overall, but I am encountering some errors that are proving difficult to identify.

The application consists of two main components:

--App :Parent
---Events :Children

In App.vue, the children component is invoked like this:

<Events :events="gameInfo" :results="results" @startNewGame="startNewGame" />

The props passed are "gameInfo" and "results", while the component listens for the "startNewGame" event.

When the application initially loads in App.vue, a function is called:

// Get Next Game
    getNextGame() {
      this.gameInfo = [];
      RouletteApi.getNextGame().then(response => {
        this.gameInfo.push({ response });
      });
   }

This children component receives and displays the data.

In the children component:

<script>
export default {
  name: "Events",
  props: ["events", "results"],
  data() {
    return {
      GameStartTime: null,
      GameId: null,
      GameUUID: null
    };
  },
  watch: {
    events: function(newVal, oldVal) {
      this.GameStartTime = newVal[0]["response"].fakeStartDelta--;
      this.GameId = newVal[0]["response"].id;
      this.GameUUID = newVal[0]["response"].uuid;
    }
  },
  created() {
    setInterval(() => {
      if (this.GameStartTime > 0) {
        this.GameStartTime = this.events[0]["response"].fakeStartDelta--;
      } else {
        this.$emit("startNewGame", this.GameUUID); -- call to parent function
      }
    }, 1000);
  }
};
</script>

I am monitoring the data, setting a timer, and triggering the "startNewGame" function from the parent when necessary, which will initiate another API call and supply the children with new data.

Upon expiration of the timer, the "startNewGame" function from the parent is invoked:

startNewGame(uuid) {
  this.startSpinning();

  RouletteApi.startNewGame(uuid).then(response => {
    if (response.result == null) {

      setTimeout(function() {
        startNewGame(uuid);
      }, 1000);

    } else {
      this.results.push({ response });

      this.gameInfo = []; -- reset previous data 
      this.getNextGame(); -- call first function mentioned above
    }
  });

This function checks if the response is null, then sets a timeout to keep calling itself until a non-null response is received. Once a non-null response arrives, it updates the results in the children, resets the gameInfo array, and calls the getNextGame() function again to fetch new data.

RouletteApi.js:

import axios from 'axios'

export default {
  getLayout() {
    return axios.get('/configuration')
      .then(response => {
        return response.data
      })
  },

  getStats() {
    return axios.get('/stats?limit=200')
      .then(response => {
        return response.data
      })
  },

  getNextGame() {
    return axios.get('/nextGame')
      .then(response => {
        return response.data
      })
  },

  startNewGame(uuid) {
    return axios.get('/game/' + uuid)
      .then(response => {
        return response.data
      })
  }
}

Errors:

Error in callback for watcher "events": "TypeError: Cannot read property 'response' of undefined"

TypeError: Cannot read property 'response' of undefined
    at VueComponent.events (Events.vue?5cf3:30)

Uncaught ReferenceError: startNewGame is not defined

The first two errors occur in the children component within the "watch" section. The last error is triggered when trying to call a function within the setInterval in the parent component.

Answer №1

The watcher appears to be executing prematurely, ahead of the completion of the API call. To troubleshoot this issue, utilize console logging to examine the new value and determine what is being retrieved. Verify that the newVal is neither null nor an empty array before assigning the values accordingly.

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 dialogue within the map function is not functioning properly

In my state, I have saved data (objects) known as workitems. When these objects are mapped out to a table, everything functions correctly. However, upon trying to implement a Dialog feature with a button that allows users to view more information about a s ...

Establishing the Default Volume within a script

I'm looking to adjust the default volume of music on my website. Currently, it plays too loudly on load, but I have a slider bar that allows users to change the volume. How can I set the default volume to be 25% of the slider? CHECK OUT MY WEBSITE! ...

What is the process for transmitting data using an Ajax Query to a Controller and subsequently displaying a new JSP page returned by the Controller?

One issue I am facing involves sending data to a Spring Boot Controller through an AJAX Query and then loading a new JSP page. When I send data to the url in the AJAX Query, which matches the URL in my controller class, it executes the code within that met ...

Retrieving information through the $.getJSON() function

As I develop a web application, I find myself in need of initializing certain parameters by fetching them using the $.getJSON() method. $.getJSON("../config/", function(data) { console.debug(data); } These values are important on a global scale with ...

Tips for adjusting the height of both an iframe and a div to fit perfectly at 100% combined

Struggling to make an iframe and div both have 100% full height on the page? I need a footer menu with 280px height, leaving the rest of the page for the iframe. After extensive research, it seems like jQuery might be necessary as CSS Flex didn't wor ...

Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console: var object = {0:0, 1:1} I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redef ...

Add a button feature to both upload and download a todo list within a JavaScript file, similar to a text file

I'm looking to enhance my simple todo list with a download and upload function. I want to be able to save the list in local storage and then upload or download it from a server code. Below is a link to my code: https://jsfiddle.net/zahrashokri/uqkn6t ...

Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this: <script>window.alert("hello");</script> When I test the site with "Gatsby ser ...

Access the menu featuring a pair of distinct buttons

I have a simple dropdown menu that can be triggered by clicking on the icon NewIcon in DropdownMenu.Trigger. Implementing this dropdown menu is straightforward, as I am using the radix library () <DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen ...

Obtaining the geographic coordinates (latitude and longitude) from a MySQL database and then transferring this information to

I'm new to this and I was wondering if there's a simple way to pass locations retrieved from PHP to Google Maps within a script in my HTML. PHP (works fine): <?php require_once "sql.php"; error_reporting(E_ALL ^ E_NOTICE); ini_set('dis ...

Steps for generating an array entry containing an ObjectId and a Number

I am a newbie when it comes to mongodb and I am attempting to create an entry like this: { "resources": [ { "amount": 1, "resource": { "_id": "61be82b9549b4ede ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Tips for resetting input and select values in VUE

In my VUE application, I have an input and a select that are displayed based on the selection of a previous input. When I enter values and change the initial input selection, I hide the second input and select to reset the form. However, even after resetti ...

Tips for activating a tooltip upon clicking instead of hovering over it:

I am currently working with tooltips and I am looking to display the tooltip message upon clicking, rather than on hover. Is there a way to make this modification? This is the code I have so far: .tooltip { position: absolute; top: 7px; margin-l ...

The JQuery ajax success callback seems to stick around forever, never getting cleaned up

Apologies for the unusual JavaScript code, as it is compiled from CoffeeScript. Whenever specific events occur in my WebApp, I trigger a callback function to initiate a JSON request: GmScreen.prototype.requestPcUpdate = function(id) { var currentU ...

Create a horizontal scrolling div with a fixed position

Even though this topic has been discussed numerous times, I have not found any solutions that work for me. My webpage has a sidebar on the left with position:fixed in CSS, and I want it to scroll horizontally along with the rest of the content. For the he ...

Providing settings to Vue.js components that have been globally registered

When registering my Vue.js components, I follow this pattern: In the index.js file of a separate reusable npm and webpack project called myComponents: import MyButtons from './src/components/my-buttons.vue' import MyInput from './src/compo ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

The functionality of my bootstrap carousel seems to be malfunctioning as the fdi-Carousel slide is

Whenever I check for errors in the Chrome console, I come across this error: Uncaught ReferenceError: $ is not defined. It seems to be related to my code. Can anyone help me identify what might be causing this issue? Below is a snippet of my code from &apo ...

Preventing JavaScript injection in Rails 3.2 js.erb files

I'm completely new to the world of Rails and I find myself lost in confusion. One particular aspect that's causing me a headache is utilizing a js.erb file to display a list of products fetched from the server. What baffles me even more is how th ...