Passing a Value from Child to Parent Function in Meteor: A Complete Guide

I am trying to pass the value of a result from a child element to its parent element. Initially, I used Session.set and Session.get which worked fine but I realize that using Sessions globally is not considered good practice. So, I attempted to utilize reactive vars or reactive dicts instead, however, they only return an object as a result. How can I extract specific data from that object or what approach should I take? (I am storing JSON data inside the ReactiveVar or Dict and I am aware that it might not be ideal with JSON. Thank you for your assistance!

Template.companyCreate.helpers({
    CompanyName : function () {
        if (Meteor.user() || Roles.userIsInRole(Meteor.user(),['admin','adminCreator'], 'companyAdmin')) {
            Meteor.call('findCompany', function(err, result) {
                if (err) {
                    console.log(err.reason)
                }
                else {
                    // Will need to handle the result here and pass it to the parent function
                }
            });
            return // Need to retrieve the result passed from the child function and return it for CompanyName
        }
        else {
            Router.go('/nemate-prava')
        }
    },

UPDATED CODE

    Template.companyCreate.onCreated(function Poruke() {
    this.message = new ReactiveVar(' ');

    let self = this;
    let user = Meteor.user();
    let companyNameHandler = Template.currentData().companyNameHandler;
    self.companyName = new ReactiveVar();

    if (user && Roles.userIsInRole(user,['admin','adminCreator'], 'companyAdmin')) {
        Meteor.call('findCompany', function(err, result) {
            if (err) {
                console.log(err.reason)
            }
            else {
                self.companyName.set(result);
                companyNameHandler(result);
                }
            });
        }
    else {
        Router.go('/nemate-prava')
    }
}); 

Template.companyCreate.helpers({
    message: () => { return Template.instance().message.get() },

    isNotInRole : function() {
        if (!Meteor.user() || !Roles.userIsInRole(Meteor.user(),['admin','adminCreator'], 'companyAdmin')) {
            return true;
        }
        else {
            return false;
        }
    },

    CompanyName : function () {
        return Template.instance().companyName.get();
    }
});

Template.companyCreate.events({
    'submit form': function(event, template) {
        var Ime = event.target.Ime.value;
        event.preventDefault();
        Meteor.call('companyCheck', Ime, function(error, result) {       
            if (error) {
                console.log(error.reason);
                template.message.set(error.reason);
                alert(error.reason);
            }
            else {
                event.target.Ime.value = "";
                console.log('Kompanija je uspesno kreirana!');
                template.message.set("Uspesno!");
            }
        })
    },
});

Method:

    'findCompany'(){
        ImeKompanije = firma.findOne({AdminID: this.userId}).ImeKompanije
        if (typeof ImeKompanije == 'undefind') {
            throw new Meteor.Error(err, "Greska!");
        }
        return ImeKompanije;

    },
});

Router:

    Router.route('/comp/:ImeKompanije', {
    name: 'companyProfile',
    template: 'companyProfile',
    waitOn: function() {
        return Meteor.subscribe('bazaFirmi', this.params.ImeKompanije)
    },
    action: function() {
        this.render('companyProfile', {
            data: function() {
                return firma.findOne({ImeKompanije: this.params.ImeKompanije});
            }
        });
    },
});

Answer №1

Alright, there's a lot going on here that we need to unpack. Let's take it step by step.

if (Meteor.user() || Roles.userIsInRole(Meteor.user(),['admin','adminCreator'], 'companyAdmin')) {

It seems like this line is supposed to check if the user is an admin, but it's actually checking if the user is logged in. If you intended to check for admin status, replace "||" with "&&".

A larger issue is that you're making a server call within a helper function. Helpers are meant to simply return data and should not have side effects like server calls or redirecting users.

To address this, let's move the server call to the onCreated() function and store the company name in a reactive variable which can then be accessed by the helper. We'll also set up a way to pass the company name back to the parent template.

Template.companyCreate.onCreated(function() {
    let self = this;
    let user = Meteor.user();
    let companyNameHandler = Template.currentData().companyNameHandler;

    self.companyName = new ReactiveVar();

    if (user && Roles.userIsInRole(user,['admin','adminCreator'], 'companyAdmin')) {
        Meteor.call('findCompany', function(err, result) {
            if (err) {
                console.log(err.reason)
            }
            else {
                self.companyName.set(result);
                companyNameHandler(result);
            }
        });
    }
    else {
        Router.go('/nemate-prava')
    }
});

Now the helper function simply returns the data stored in the template's reactive variable:

Template.companyCreate.helpers({
    CompanyName : function () {
        return Template.instance().companyName.get();
    }
});

Finally, we need to set up a handler to pass the data back to the parent template. It's best practice to avoid the client reaching back up to its parent, so we'll have the parent template provide a function that the child can call when ready. Here's how you can implement it:

<template name="Parent">
    {{> companyCreate companyNameHandler=getCompanyNameHandler}}
</template>

Template.Parent.helpers({
    getCompanyNameHandler() {
        let template = Template.instance();

        return function(companyName) {
            console.log(companyName);
            // You can access the parent template using the closure "template"
        }
    }
});

The parent template's helper function returns a callback function that will execute in the parent's scope when called by the child. By setting up a variable "template" in the closure, you can access reactive vars belonging to the parent template.

UPDATE: If the handler is not available directly within the Meteor.call() scope, you can try accessing it through a reactive variable as shown below:

Template.companyCreate.onCreated(function() {
    let self = this;
    let user = Meteor.user();
    self.companyNameHandler = new ReactiveVar(Template.currentData().companyNameHandler);

    self.companyName = new ReactiveVar();

    if (user && Roles.userIsInRole(user,['admin','adminCreator'], 'companyAdmin')) {
        Meteor.call('findCompany', function(err, result) {
            if (err) {
                console.log(err.reason)
            }
            else {
                self.companyName.set(result);
                let fn = self.companyNameHandler.get();
                fn(result);
            }
        });
    }
    else {
        Router.go('/nemate-prava')
    }
});

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

Optimizing Load Times for Twitch.Tv API in CakePHP

Currently, I am working on the following code snippet: public function fetchUser($username) { $result = array(); $data = array(); $httpSocket = new HttpSocket(); $url = $this->baseUrl . $username . $this->apiKey; ...

Steps for deactivating an eventhandler while another is being triggered:

There are two event listeners attached to a single input field. One triggers on change, while the other activates when selecting an autocomplete suggestion from Google. The issue arises when interacting with an autocompletion option as both handlers execut ...

Experiencing difficulties when attempting to launch a React application and Express/Node.js backend on a shared port

I'm trying to set up my react front-end on localhost:5000, with API requests going to localhost:5000/api/some-path. After looking at similar questions, I've come to understand the following: Include a proxy in the package.json file Serve st ...

Arranging elements in HTML for Manipulating with JavaScript

I haven't started coding yet, but I'm contemplating the overall strategy. My front end is primarily composed of HTML tables, giving it an Excel-like appearance. I am considering generating default pages and then using JavaScript to dynamically m ...

"Utilize Javascript to upload a picture and showcase it on your website

<!DOCTYPE html> <html> <head> <title>Unique Webpage!</title> <meta charset=utf-8 />                       <link rel="stylesheet" href="styles/customcss.css" /> <script src="j ...

How can I customize the list view and enable the OOTB Preview feature?

In my document library, I have successfully formatted the list view. While this has been effective, we are now missing out on the default functionality of SharePoint online where you can preview files within the main window with all the added benefits such ...

What is the optimal method for importing a JSONObject from a JSON file?

Is there a more efficient way to load a JSON file into a JSONObject? Currently, I am utilizing json-lib for this task. Here is my current approach which results in an exception being thrown: XMLSerializer xml = new XMLSerializer(); JSON json = xml.readF ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Exploring the process of extracting a JSON array from HttpServletRequest

I am completely new to servlets and I'm having trouble extracting a JSON array from the HttpServletRequest This is the JSON data I'm sending to Java: page: 1 start: 0 limit: 20 sort: [{"property":"fiscalYear","direction":"DESC"}] protected vo ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

The JSON parser has exceeded the permitted memory allocation of 134217728 bytes and cannot allocate additional 72 bytes, resulting in an error on line 14 of the /home/migrande/public_html/sample.php

Could someone lend a hand with this code? I'm trying to retrieve all the data from the database using PHP JSON... but how can I make it work? <?php require_once 'include/db_functions.php'; $db = new DB_Functions(); $user = $ ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Having trouble with the preview feature when resizing images

Before trying to implement the JSFiddle was working correctly: http://jsfiddle.net/qa9m7t33/ However, after attempting to implement it, I encountered some issues: http://jsfiddle.net/z1k538sm/ While trying to resize an image, I realized that this example ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

How to insert text into a text input using onKeyPress in react.js

I am looking to simulate a typing effect where the phrase 'Surveillance Capitalism' is inputted letter by letter into a text input field as a user types. However, I encounter an issue when trying to add each individual letter into the input; I re ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

The function 'json_each' is not available

I'm encountering an issue where the json_each function is not recognized. This is happening in postgresql 9.3 and I can't figure out what's causing it. Any help would be greatly appreciated. select * from json_each(( select ed.result ...

Identify all paths with or without the .html suffix, excluding static resources

I am working on configuring a universal handler for requests that do not pertain to images or favicons. I want this handler to manage paths like /index, /index.html, /user/123, and similar, while excluding /favicon.ico, /sunflower.png, /images/starfish.png ...

Sign up a new user using Passport JS

Looking to utilize passport.js for adding a new user from the signup page. The signup form is as follows: <form id="Signup-form" name="SignupForm" action="/signup" method="post"/> <input type="text" id="firstname" name="Firstname" > <input ...