Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component.

The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute this function only if there is actually data returned from the API service.

axios.get('/class')
    .then((response) => {
        console.log(response.data.results)
        response.data.results.forEach(element => {
            const object = {
                clientId: element.client.objectId,
                price: element.price || 0,
                driverId: element.objectId || null
            }
            this.serviceData.tripsInfo.push(object) // The object that will be sent to the component
           ...

HTML :

<class title="List of class" :points="serviceData"/>

class component:

props: {
    points: {} // This is where the layout data will be stored
},
mounted () {
    console.log(this.points)
    const reducer = (accumulator, currentValue) => accumulator + currentValue
    this.totalPrices = this.points.class.map(x => x.price).reduce(reducer) // Facing an issue here ("Reduce of empty array with no initial value")
},

Answer №1

When a watcher function is defined, it will monitor any prop or data property with the same name and execute the designated function every time that particular dependency updates.

props: {
    points: Object
},
watch: {
    points() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        this.totalPrices = this.points.class.map(x => x.price).reduce(reducer)
    }
}

Essentially, once the data in points is loaded, the reducer function will be triggered.

Alternatively, you can simplify this by using a computed property:

computed: {
    totalPrices: function() {
        const reducer = (accumulator, currentValue) => accumulator + currentValue
        return this.points.class.map(x => x.price).reduce(reducer)
    }
}

Answer №2

One possible solution is to utilize the V-if directive, as shown below:

<class title="" v-if="serviceData.class.length > 0" :points="serviceData"/> 

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

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

What is the method for utilizing underscores in Visual Studio Code without the need to "enable" them beforehand?

I attempted to utilize underscore in Visual Studio Code and found that it only works if I include this line of code at the beginning: var _ = require('underscore'); The output functions properly with this code in place. However, if I remove it, ...

How can JavaScript be used to modify the locale of a web browser?

Is it possible to programmatically set the window.navigator.language using AngularJS? I am exploring different methods to achieve this. At the moment, I rely on a localization service to handle my i18n localization switching. ...

Do async functions in javascript function synchronously in reality?

I am currently exploring the inner workings of asynchronous code in Javascript. From my understanding, there exists a single thread in JS responsible for executing tasks in a queue. It can progress to the next task only after finishing the current one, whe ...

What steps should I take to generate a 2-Dimension Input Array from scratch?

I am working on a project that involves creating a 2-Dimensional array of text-based numerical inputs. I aim to use the standard HTML input type box for this purpose: <input type="text"> The number of rows and columns in the array will depend o ...

JavaScript: what is the method to add a paragraph when the condition is not met?

I am currently working on a project that involves checking if a student is actively engaged in an online journal. This is done by tracking the student's progress using a unique userId. If the student's userId is not found in the JSON data returne ...

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

Guide on transitioning from a WebGL renderer to a canvas renderer in three.js

My goal is to display a scene using either a WebGL renderer or a canvas renderer in three.js (version 69). This is the code I am using: <!DOCTYPE html> <html> <head> <script src="./libs/three.js"></script> <scri ...

The Model.function method is not a valid function that can be used within a router

Currently facing a challenge with my router setup. I have exported the function as shown in the code snippet below. This is the Model I am using: "use strict"; var mongoose = require('mongoose'); var bcrypt = require("bcryptjs"); var Schema = m ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

Sending data through a form using AJAX and PHP

Greetings! I've developed a page that allows users to view results for a specific tournament and round. The user will first select a sport, which will then populate the available tournaments based on the sport selection. Following this, the user can ...

Transferring information using express

Currently, my Express server is up and running and it's set to send an HTML file from the public folder of my project. The issue arises when I try to initiate a request from a client script linked in this HTML file to send data back to the server. Des ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

Pass data to PHP using AJAX

Is it possible to pass the variable rowNumber to the PHP file dataSource in this code? function getData(dataSource, divID,rowNumber) { if(XMLHttpRequestObject) { var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSo ...

Ways to refresh a container

How do I update the box below... <div className="container team-member-tasks"> <header className="header-box"> <h1>Team Member Tasks</h1> ...after marking a task as complete using the script below. ...

Error: JSON parsing encountered an unexpected token at character 182704

While working on a Vue Application, an error occurred when running npm run build in the GitHub Actions workflow. The specific error message was: SyntaxError: Unexpected token in JSON at position 182704 at JSON.parse (<anonymous>) at /home/ru ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...