Blaze.renderWithData - how to automatically update template if data changes? - meteor

I have built a list using Meteor. I do not want the entire list to be reactive, i.e. auto-update when the data changes. However, I do want the title of a list item to update if the data relating to that list item changes. I am inserting the list items using Blaze.renderWithData, so how can I achieve this?

Use two helpers, a non-reactive one which returns the cursor and a reactive one which returns the title. To make something non-reactive, use Tracker.nonreactive, (related question).
In the following contrived example I'm returning a reactive title that includes the cursor count if non-zero while the cursor returned from the helper is non-reactive.
subHandle = Meteor.subscribe('mySubscription');
Template.foo.helpers({
cursor: function(){
if ( subHandle.ready() ) return Tracker.nonreactive(function() {
return myCollection.find(query,options);
});
}),
title: function(){
var nDocs = myCollection.find(query,options).count();
if ( nDocs ) return "Title (" + nDocs + ")";
else return "Title";
}
});
Update:
Modified to deal with the subscription handle being ready so that the nonreactive function is called for the first time with a ready subscription.
Here's a Meteorpad with a working example. You can see that the total points updates as you add points to players but the player scores and sort never change.

Related

Click a random row in a table cypress

I have a page in my app that shows outstanding defects for a user. I want a cypress to click on one of the rows, this takes you to a detail page.
I am able to select the table rows using
cy.get('[data-cy=faultsTable] tr').then(($tr)=>{
})
this correctly gets me 4 elements as expected. But I can't work out how to randomly choose one of them, as the .then wants to execute on each in turn.
I want to
a) get the defect id from
b) click the row.
Any suggestions will be gratefully received
There might be a better approach to this problem, but below is from my thought. If the number of defect Id records are less and are static, I mean from the table, you could probably pass those defect id into an array and return the defect id randomly.
Option:1
I have got a sample.js file in the /support folder where I have added the randomDefectId function.
module.exports ={
randomDefectId: function(){
var defect= ['10756', '10780', '19001', '21007', '25001', '27001'];
var item = defect[Math.floor(Math.random()*defect.length)];
return item;
}
}
Then I have import them into my test spec
var rand = require('../../support/sample.js');
Below is my test where I am receiving the rand.randomDefectId() into a const ranNumber
describe('Get the defect id', function(){
it('Check whether the defect id', function(){
const ranNumber = rand.getRandomNumber();
cy.visit('/');
console.log("Some number:"+ranNumber );
cy.get('#tableID>tbody>tr>td').contains(ranNumber).click()
// rest of the test step continues here...
})
})
Option:2
But if there are a large list of defect id inside the table, then you need a dynamic way to get the defect id, I haven't tried the below script, but you could give a try..
randomDefectId: function(){
let table = undefined;
Cypress.$("#tableID>tbody>tr").each(function() {
var newArr = Cypress.$(this).find("td:last-child").html();
table = newArr;
});
return table;
}
If there is better way of achieving this, I would like to know and share

Returned value from Meteor Helper not showing up in template

I have a Meteor Helper that does a GET request and am supposed to get response back and pass it back to the Template, but its now showing up the front end. When I log it to console, it shows the value corerctly, for the life of mine I can't get this to output to the actual template.
Here is my helper:
UI.registerHelper('getDistance', function(formatted_address) {
HTTP.call( 'GET', 'https://maps.googleapis.com/maps/api/distancematrix/json? units=imperial&origins=Washington,DC&destinations='+formatted_address+'&key=MYKEY', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
var distanceMiles = response.data.rows[0].elements[0].distance.text;
console.log(response.data.rows[0].elements[0].distance.text);
return distanceMiles;
}
});
});
In my template I pass have the following:
{{getDistance formatted_address}}
Again, this works fine and shows exactly what I need in the console, but not in the template.
Any ideas what I'm doing wrong?
I posted an article on TMC recently that you may find useful for such a pattern. In that article the problem involves executing an expensive function for each item in a list. As others have pointed out, doing asynchronous calls in a helper is not good practice.
In your case, make a local collection called Distances. If you wish, you can use your document _id to align it with your collection.
const Distances = new Mongo.collection(); // only declare this on the client
Then setup a function that either lazily computes the distance or returns it immediately if it's already been computed:
function lazyDistance(formatted_address){
let doc = Distances.findOne({ formatted_address: formatted_address });
if ( doc ){
return doc.distanceMiles;
} else {
let url = 'https://maps.googleapis.com/maps/api/distancematrix/json';
url += '?units=imperial&origins=Washington,DC&key=MYKEY&destinations=';
url += formatted_address;
HTTP.call('GET',url,{},(error,response )=>{
if ( error ) {
console.log( error );
} else {
Distances.insert({
formatted_address: formatted_address,
distanceMiles: response.data.rows[0].elements[0].distance.text
});
}
});
}
});
Now you can have a helper that just returns a cached value from that local collection:
UI.registerHelper('getDistance',formatted_address=>{
return lazyDistance(formatted_address);
});
You could also do this based on an _id instead of an address string of course. There's a tacit assumption above that formatted_address is unique.
It's Meteor's reactivity that really makes this work. The first time the helper is called the distance will be null but as it gets computed asynchronously the helper will automagically update the value.
best practice is not to do an async call in a helper. think of the #each and the helper as a way for the view to simply show the results of a prior calculation, not to get started on doing the calculation. remember that a helper might be called multiple times for a single item.
instead, in the onCreated() of your template, start the work of getting the data you need and doing your calculations. store those results in a reactive var, or reactive array. then your helper should do nothing more than look up the previously calculated results. further, should that helper be called more times than you expect, you don't have to worry about all those additional async calls being made.
The result does not show up because HTTP.call is an async function.
Use a reactiveVar in your case.
Depending on how is the formated_address param updated you can trigger the getDistance with a tracker autorun.
Regs
Yann

What's the best way to display data when user input changes in Meteor (datepicker)?

I don't know how else to word this, but basically I'm implementing a datepicker, so the user can choose the range for which the data is displayed. The user picks a start data and ending date and with that, I re-run a gigantic function that is located in the lib folder to re-run and change all the data that is displayed via Meteor helpers on the main page.
The dates that the user picks are stored in Session variables, which are accessed in the function that I intended. The function runs, but no changes are displayed on client (but these changes are true in the console and I can see the changes being made via console.log statements I have throughout the function).
This is what the datepicker's onRendered function looks like:
Template.dashboard.onRendered(function(){
// Date picker
$(function() {
function cb(start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
var startDate = start.format('MMMM D, YYYY');
Session.set("startingDate", startDate)
var endDate = end.format('MMMM D, YYYY');
Session.set("endingDate", endDate);
}
var firstDate = dates[0];
var lastItem = dates.length-1;
var lastDate = dates[lastItem]
cb(moment(firstDate), moment(lastDate));
$('#reportrange').daterangepicker({
ranges: {
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')]
}
}, cb);
});
});
The Tracker.autorun:
Tracker.autorun(function(){
libFxn();
});
libFxn() is the rather large function in the lib folder that I call in the Tracker. So, whenever one of the Session variable changes due to user input, the Tracker.autorun fires and function is run and values are being changed, which I am able to see via console. However, on client, I don't see the changes.
That leaves me in a dilemma: I need to show the user the resulting data changes based on the input, but:
1) Changes are not seen in client, even though function in lib folder is being executed.
2) I can't use document.location.reload(true); or refresh the page in any way because when the page refreshes, the session variables are restored to default values (which is first date and last date of the dates array that I have on hand).
So I need to figure out a way to send the user's date input data to the function in the lib folder in a way that will show the changes in the client/template that doesn't involve Sessions if the page has to be refreshed.
If anyone can give me hints or tips, I would be grateful.
Here is an example of one helper, which is basically identical to all others minus the different variables it calls (all these variables are in the libFxn() function and are populated there and called via these helper functions):
WinRate: function(){
if(Number((((wins/gamesPlayed))))){
return numeral((wins/gamesPlayed)).format('0%');
} else if(Number((((wins/gamesPlayed)))) === 0){
return "0%"
} else{
return "n/a";
}
}
From comments above you are not making the variables themselves reactive. You can do this using the Tracker.Dependency.
In your lib file you will want to use globalsDep = new Tracker.Dependency; or similar, you will probably want to have one for each type of outcome from your function i.e. if you can modify 10 variables independently then you will want 10, a new dependency for each one otherwise you will re-run every helper that depends on them each time any value changes. if you want everything to re-run of course just use one:
globalsDep = new Tracker.Dependency;
Each place you modify the relevant variable (or at the end of your function if you only want one dependency) you need to tell the dependency that it has become invalid and needs to recompute
globalsDep.changed();
And then in each of the helpers you want to rerun you call the depends function:
globalsDep.depends()
And you should see them running straight away in the view. Simple example below:
/****************
** In Lib File **
****************/
globalsDep = new Tracker.Dependency;
xDep = new Tracker.Dependency;
x = 15;
y = 10;
t = 0;
myBigLongFunction = function(){
x = x + 5;
y = y + 1;
t = x + y;
console.log('Changing Values', x, y, t);
globalsDep.changed();
if (x > 20)
xDep.changed();
}
/****************
** In JS File **
****************/
Template.main.helpers({
testGlobalReactive: function(){
globalsDep.depend();
console.log('All vars rerun');
return {t:t, x:x, y:y};
},
testXReactive: function(){
xDep.depend();
console.log('X rerun');
return x;
}
});
/****************
** In HTML File **
****************/
<template name="main">
<div style="min-height:200px;width:100%;background-color:lightgrey;">
{{#with testGlobalReactive}}
X:{{x}}<br><br>
Y:{{y}}<br><br>
T:{{t}}<br><br>
{{/with}}
X Individual: {{testXReactive}}
</div>
</template>
Although I would caution against having client state in this way, you would be better leveraging the reactivity of collections and ensuring everything is synched with the server through them, having this sort of data stored on the client will not be persistent anywhere and cannot be trusted in any manner as client can modify global variables at will. If you are already setting this data from collections in the function ignore the last but you may still want to consider accessing the data either in iron router data field or at a template level direct from collection as it will be reactive by default without need for the Tracker.dependency :D

How do I reverse order based on my unique ids from push() [duplicate]

I'm trying to test out Firebase to allow users to post comments using push. I want to display the data I retrieve with the following;
fbl.child('sell').limit(20).on("value", function(fbdata) {
// handle data display here
}
The problem is the data is returned in order of oldest to newest - I want it in reversed order. Can Firebase do this?
Since this answer was written, Firebase has added a feature that allows ordering by any child or by value. So there are now four ways to order data: by key, by value, by priority, or by the value of any named child. See this blog post that introduces the new ordering capabilities.
The basic approaches remain the same though:
1. Add a child property with the inverted timestamp and then order on that.
2. Read the children in ascending order and then invert them on the client.
Firebase supports retrieving child nodes of a collection in two ways:
by name
by priority
What you're getting now is by name, which happens to be chronological. That's no coincidence btw: when you push an item into a collection, the name is generated to ensure the children are ordered in this way. To quote the Firebase documentation for push:
The unique name generated by push() is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.
The Firebase guide on ordered data has this to say on the topic:
How Data is Ordered
By default, children at a Firebase node are sorted lexicographically by name. Using push() can generate child names that naturally sort chronologically, but many applications require their data to be sorted in other ways. Firebase lets developers specify the ordering of items in a list by specifying a custom priority for each item.
The simplest way to get the behavior you want is to also specify an always-decreasing priority when you add the item:
var ref = new Firebase('https://your.firebaseio.com/sell');
var item = ref.push();
item.setWithPriority(yourObject, 0 - Date.now());
Update
You'll also have to retrieve the children differently:
fbl.child('sell').startAt().limitToLast(20).on('child_added', function(fbdata) {
console.log(fbdata.exportVal());
})
In my test using on('child_added' ensures that the last few children added are returned in reverse chronological order. Using on('value' on the other hand, returns them in the order of their name.
Be sure to read the section "Reading ordered data", which explains the usage of the child_* events to retrieve (ordered) children.
A bin to demonstrate this: http://jsbin.com/nonawe/3/watch?js,console
Since firebase 2.0.x you can use limitLast() to achieve that:
fbl.child('sell').orderByValue().limitLast(20).on("value", function(fbdataSnapshot) {
// fbdataSnapshot is returned in the ascending order
// you will still need to order these 20 items in
// in a descending order
}
Here's a link to the announcement: More querying capabilities in Firebase
To augment Frank's answer, it's also possible to grab the most recent records--even if you haven't bothered to order them using priorities--by simply using endAt().limit(x) like this demo:
var fb = new Firebase(URL);
// listen for all changes and update
fb.endAt().limit(100).on('value', update);
// print the output of our array
function update(snap) {
var list = [];
snap.forEach(function(ss) {
var data = ss.val();
data['.priority'] = ss.getPriority();
data['.name'] = ss.name();
list.unshift(data);
});
// print/process the results...
}
Note that this is quite performant even up to perhaps a thousand records (assuming the payloads are small). For more robust usages, Frank's answer is authoritative and much more scalable.
This brute force can also be optimized to work with bigger data or more records by doing things like monitoring child_added/child_removed/child_moved events in lieu of value, and using a debounce to apply DOM updates in bulk instead of individually.
DOM updates, naturally, are a stinker regardless of the approach, once you get into the hundreds of elements, so the debounce approach (or a React.js solution, which is essentially an uber debounce) is a great tool to have.
There is really no way but seems we have the recyclerview we can have this
query=mCommentsReference.orderByChild("date_added");
query.keepSynced(true);
// Initialize Views
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mManager = new LinearLayoutManager(getContext());
// mManager.setReverseLayout(false);
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mManager);
I have a date variable (long) and wanted to keep the newest items on top of the list. So what I did was:
Add a new long field 'dateInverse'
Add a new method called 'getDateInverse', which just returns: Long.MAX_VALUE - date;
Create my query with: .orderByChild("dateInverse")
Presto! :p
You are searching limitTolast(Int x) .This will give you the last "x" higher elements of your database (they are in ascending order) but they are the "x" higher elements
if you got in your database {10,300,150,240,2,24,220}
this method:
myFirebaseRef.orderByChild("highScore").limitToLast(4)
will retrive you : {150,220,240,300}
In Android there is a way to actually reverse the data in an Arraylist of objects through the Adapter. In my case I could not use the LayoutManager to reverse the results in descending order since I was using a horizontal Recyclerview to display the data. Setting the following parameters to the recyclerview messed up my UI experience:
llManager.setReverseLayout(true);
llManager.setStackFromEnd(true);
The only working way I found around this was through the BindViewHolder method of the RecyclerView adapter:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final SuperPost superPost = superList.get(getItemCount() - position - 1);
}
Hope this answer will help all the devs out there who are struggling with this issue in Firebase.
Firebase: How to display a thread of items in reverse order with a limit for each request and an indicator for a "load more" button.
This will get the last 10 items of the list
FBRef.child("childName")
.limitToLast(loadMoreLimit) // loadMoreLimit = 10 for example
This will get the last 10 items. Grab the id of the last record in the list and save for the load more functionality. Next, convert the collection of objects into and an array and do a list.reverse().
LOAD MORE Functionality: The next call will do two things, it will get the next sequence of list items based on the reference id from the first request and give you an indicator if you need to display the "load more" button.
this.FBRef
.child("childName")
.endAt(null, lastThreadId) // Get this from the previous step
.limitToLast(loadMoreLimit+2)
You will need to strip the first and last item of this object collection. The first item is the reference to get this list. The last item is an indicator for the show more button.
I have a bunch of other logic that will keep everything clean. You will need to add this code only for the load more functionality.
list = snapObjectAsArray; // The list is an array from snapObject
lastItemId = key; // get the first key of the list
if (list.length < loadMoreLimit+1) {
lastItemId = false;
}
if (list.length > loadMoreLimit+1) {
list.pop();
}
if (list.length > loadMoreLimit) {
list.shift();
}
// Return the list.reverse() and lastItemId
// If lastItemId is an ID, it will be used for the next reference and a flag to show the "load more" button.
}
I'm using ReactFire for easy Firebase integration.
Basically, it helps me storing the datas into the component state, as an array. Then, all I have to use is the reverse() function (read more)
Here is how I achieve this :
import React, { Component, PropTypes } from 'react';
import ReactMixin from 'react-mixin';
import ReactFireMixin from 'reactfire';
import Firebase from '../../../utils/firebaseUtils'; // Firebase.initializeApp(config);
#ReactMixin.decorate(ReactFireMixin)
export default class Add extends Component {
constructor(args) {
super(args);
this.state = {
articles: []
};
}
componentWillMount() {
let ref = Firebase.database().ref('articles').orderByChild('insertDate').limitToLast(10);
this.bindAsArray(ref, 'articles'); // bind retrieved data to this.state.articles
}
render() {
return (
<div>
{
this.state.articles.reverse().map(function(article) {
return <div>{article.title}</div>
})
}
</div>
);
}
}
There is a better way. You should order by negative server timestamp. How to get negative server timestamp even offline? There is an hidden field which helps. Related snippet from documentation:
var offsetRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/.info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});
To add to Dave Vávra's answer, I use a negative timestamp as my sort_key like so
Setting
const timestamp = new Date().getTime();
const data = {
name: 'John Doe',
city: 'New York',
sort_key: timestamp * -1 // Gets the negative value of the timestamp
}
Getting
const ref = firebase.database().ref('business-images').child(id);
const query = ref.orderByChild('sort_key');
return $firebaseArray(query); // AngularFire function
This fetches all objects from newest to oldest. You can also $indexOn the sortKey to make it run even faster
I had this problem too, I found a very simple solution to this that doesn't involved manipulating the data in anyway. If you are rending the result to the DOM, in a list of some sort. You can use flexbox and setup a class to reverse the elements in their container.
.reverse {
display: flex;
flex-direction: column-reverse;
}
myarray.reverse(); or this.myitems = items.map(item => item).reverse();
I did this by prepend.
query.orderByChild('sell').limitToLast(4).on("value", function(snapshot){
snapshot.forEach(function (childSnapshot) {
// PREPEND
});
});
Someone has pointed out that there are 2 ways to do this:
Manipulate the data client-side
Make a query that will order the data
The easiest way that I have found to do this is to use option 1, but through a LinkedList. I just append each of the objects to the front of the stack. It is flexible enough to still allow the list to be used in a ListView or RecyclerView. This way even though they come in order oldest to newest, you can still view, or retrieve, newest to oldest.
You can add a column named orderColumn where you save time as
Long refrenceTime = "large future time";
Long currentTime = "currentTime";
Long order = refrenceTime - currentTime;
now save Long order in column named orderColumn and when you retrieve data
as orderBy(orderColumn) you will get what you need.
just use reverse() on the array , suppose if you are storing the values to an array items[] then do a this.items.reverse()
ref.subscribe(snapshots => {
this.loading.dismiss();
this.items = [];
snapshots.forEach(snapshot => {
this.items.push(snapshot);
});
**this.items.reverse();**
},
For me it was limitToLast that worked. I also found out that limitLast is NOT a function:)
const query = messagesRef.orderBy('createdAt', 'asc').limitToLast(25);
The above is what worked for me.
PRINT in reverse order
Let's think outside the box... If your information will be printed directly into user's screen (without any content that needs to be modified in a consecutive order, like a sum or something), simply print from bottom to top.
So, instead of inserting each new block of content to the end of the print space (A += B), add that block to the beginning (A = B+A).
If you'll include the elements as a consecutive ordered list, the DOM can put the numbers for you if you insert each element as a List Item (<li>) inside an Ordered Lists (<ol>).
This way you save space from your database, avoiding unnecesary reversed data.

Using JQuery to set 'dirty' elements back to original values

I have a Javascript object that basically represents a Row in an .NET GridView.
When a user clicks on any row in the grid, all the input elements in that row are 'enabled'.(ie 'Edit' mode).
I run this code depending on which row is selected
$(":input", this._row).attr('disabled', true);
or
$(":input", this._row).removeAttr('disabled');
So far so good. Now, I want to keep track of the values in that row before a user enters the 'Edit Mode', so i can restore the original values if they decide to click out of that row without saving any changes that they made.
So i capture the original values in an array by doing this:
var $inputs = $(":input", this._row);
var values = {};
$inputs.each(function(i, el) { values[el.name] = $(el).val(); });
the 'values' array now looks like this:
ctl00$ContentPlaceHolder1$resultsGrid$ctl04$COMPONENT1 "56"
ctl00$ContentPlaceHolder1$resultsGrid$ctl04$COMPONENT2 "98"
ctl00$ContentPlaceHolder1$resultsGrid$ctl04$COMPONENT3 "08"
ctl00$ContentPlaceHolder1$resultsGrid$ctl04$COMPONENT4 "200"
Great so far. The user may then modify these values, but decide not to save the changes.
So i need to restore this row back to it's orignal values from the 'values' array.
Can someone tell me the best way to do this? Im hoping it's something simple, but i'm no jquery expert, yet..
thanks
You can use the 'data method' (http://docs.jquery.com/Internals/jQuery.data) to store relevant data along with the element.
Something like:
//Call this function for each row after the page has loaded.
function storeOriginalData(row)
{
var $inputs = $(":input", row);
//For each input element inside the table row, we store it's original value
//using the 'data' method of jQuery.
$inputs.each(function(i, el) { $(el).data('oldValue', el.val()); });
}
//Call this function from the reset button code.
function resetOriginalData(row)
{
var $inputs = $(":input", row);
//Now we get the original value using the data method and store it in the input element.
$inputs.each(function(i, el) { $(el).val($el.data('oldValue'));
};
This way, you will avoid the maintenance of the 'values' object for each row.
EDIT:
Modified code with more details and how it works.
I haven't had the time to set up a test, but off of the top of my head I would try:
$inputs.each(function(i, el){ $(el).val(values[el.name]); });
Assuming you have already checked that values have been stored.
Could you not copy the row html and store it, and then if they changed there mind you could just restore the original row?

Resources