I've been having issues with a synchronized arrays on angularfire. I'm on angularfire 1.1.3 with firebase 2.3.1.
I have a query
var arr = $firebaseArray(ref.limitToFirst(5));
and the behavior I've seen up until now is that when I call
arr.$remove(0)
the next object that would be returned by the query gets loaded into the synchronized array automatically. This essentially makes the array a sliding window over the query response - it always has the same number of elements.
Since last week, that behavior seems to have changed, and I get two different cases:
1: Either arr does get loaded with 5 items, but after calling arr.$remove five times, the array is empty - which would be normal behavior on a JavaScript array, but isn't what I'd been seeing before on an AngularFire synchronized array.
2: Or arr is loaded but then disappears, i.e. in the code:
arr.$loaded(function(){
\\ break
})
If I break in the call back, arr does have five items, corresponding to data on Firebase, but at the end of the Angular digest loop, arr is an empty array.
Demo: This plunker shows behavior 1
So my questions are:
Was I relying on a behavior that was not officially part of the API?
Has that behavior changed?
What explains the last point (the firebase array having items on $loaded but then ending up empty?)
Update
It seems that behavior 2 happens after behavior 1 - more precisely: after getting to an empty synchronized array, if I reload the page, then I get a nonempty array in the callback of arr.$loaded but an empty array in the end.
Could that mean that firebase itself gets "stuck"?
I'll try to to reproduce that in the plunker.
This should be fixed now. Sorry for the inconvenience!
Related
I'm using charts.js, where I want to add one datarow per minute. Hence to avoid a complete redraw, Im using some ajax and just pushing a new element to the chart.
Pushing VALUES works fine, however, pushing to the label-array shows very strange behaviour. I'v now tried everything from a simple push upto iteratively cloning the whole array, copy all values, replacing the whole array... The result is still the same.
The added element seems to be always end up with index 0, therefore ending up left in the chart, rather than on the right side.
Upon initial pageload, the data that is existing is loaded as a json-array, which works as expected, for example:
var labels = ["16:00", "16:01", "16:02"]
Now, using some ajax, I retrieve a new Dataset for 16:03. Pushing that label to the array like this:
...
labels.push("16:03");
console.log(labels);
...
and inspecting it in the browser afterwards leads to the following strange view:
The stringified representation looks as expected:
(4) ["16:00", "16:01", "16:02", "16:03"]
But when expanding the view in chrome, the result is:
0: "16:03"
1: "16:00"
2: "16:01"
3: "16:02"
So, iterating the array by using index-values obviously leads to a different result than using .toString(). I have no idea what is happening here. I'm mainly confused, why the stringified version looks different than the actual drill down on indexes?
Running a vanilla-example of these steps leads to the desired result. So it has to do something with the "context" of that array. But I have no idea where to start digging ;)
Here's a screenshot
edit:
Following the example over here, it should work like that...
https://www.chartjs.org/docs/latest/developers/updates.html
Comment of #CBroe made me figure it out:
Uppon initial loading, I did not outline the labels explicit, because there i'm having whole objects like {x:"16:00", temp="20", rain="0"} i'm feeding the datarows of chart.js with.
Now, when altering the label-array, chart-js seems to apply the following logic:
Labels-Array is a dedicated Array that EXISTS but is empty if not explicit defined.
In the Getter of that array, Any Labels derived from data-objects are appended to the array.
hence, pushing to the actual array starts with index "0" if it's inititially empty. But looking at the result of the getter then delivers the static array + any required label derived from the data objects given.
Now outlining the labels-array explicit as well, this resolves the issue.
I would like to create two queries, with pagination option. On the first one I would like to get the first ten records and the second one I would like to get the other all records:
.startAt(0)
.limit(10)
.startAt(9)
.limit(null)
Can anyone confirm that above code is correct for both condition?
Firestore does not support index or offset based pagination. Your query will not work with these values.
Please read the documentation on pagination carefully. Pagination requires that you provide a document reference (or field values in that document) that defines the next page to query. This means that your pagination will typically start at the beginning of the query results, then progress through them using the last document you see in the prior page.
From CollectionReference:
offset(offset) → {Query}
Specifies the offset of the returned results.
As Doug mentioned, Firestore does not support Index/offset - BUT you can get similar effects using combinations of what it does support.
Firestore has it's own internal sort order (usually the document.id), but any query can be sorted .orderBy(), and the first document will be relative to that sorting - only an orderBy() query has a real concept of a "0" position.
Firestore also allows you to limit the number of documents returned .limit(n)
.endAt(), .endBefore(), .startAt(), .startBefore() all need either an object of the same fields as the orderBy, or a DocumentSnapshot - NOT an index
what I would do is create a Query:
const MyOrderedQuery = FirebaseInstance.collection().orderBy()
Then first execute
MyOrderedQuery.limit(n).get()
or
MyOrderedQuery.limit(n).get().onSnapshot()
which will return one way or the other a QuerySnapshot, which will contain an array of the DocumentSnapshots. Let's save that array
let ArrayOfDocumentSnapshots = QuerySnapshot.docs;
Warning Will Robinson! javascript settings is usually by reference,
and even with spread operator pretty shallow - make sure your code actually
copies the full deep structure or that the reference is kept around!
Then to get the "rest" of the documents as you ask above, I would do:
MyOrderedQuery.startAfter(ArrayOfDocumentSnapshots[n-1]).get()
or
MyOrderedQuery.startAfter(ArrayOfDocumentSnapshots[n-1]).onSnapshot()
which will start AFTER the last returned document snapshot of the FIRST query. Note the re-use of the MyOrderedQuery
You can get something like a "pagination" by saving the ordered Query as above, then repeatedly use the returned Snapshot and the original query
MyOrderedQuery.startAfter(ArrayOfDocumentSnapshots[n-1]).limit(n).get() // page forward
MyOrderedQuery.endBefore(ArrayOfDocumentSnapshots[0]).limit(n).get() // page back
This does make your state management more complex - you have to hold onto the ordered Query, and the last returned QuerySnapshot - but hey, now you're paginating.
BIG NOTE
This is not terribly efficient - setting up a listener is fairly "expensive" for Firestore, so you don't want to do it often. Depending on your document size(s), you may want to "listen" to larger sections of your collections, and handle more of the paging locally (Redux or whatever) - Firestore Documentation indicates you want your listeners around at least 30 seconds for efficiency. For some applications, even pages of 10 can be efficient; for others you may need 500 or more stored locally and paged in smaller chucks.
I have a domino view with an amount column but some values are empty...and need to be. The problem is that the #Sum works fine until I have an empty value then it stops summing.
eg: if the values are 5,5,"" and 5 I get a sum of 10 and not 15.
I've traced the problem to the #DbLookup which is that it stops building the return array when it encounters a blank value. There is no built in method of dealing with null values.
https://www.ibm.com/support/knowledgecenter/en/SSVRGU_9.0.1/reference/r_wpdr_atfunctions_dblookup_r.html
To make things harder, #dbLookup returns a string if only one is found or an array if more than one are found. If the values are 5,5,"" and 5 it returns an array of 2 values.
var alloc = #Sum(#DbLookup(#DbName(), "SubForms",MainFrmID , "ca_ca_ca_ca_amount"));
if (isNaN(alloc)){
return "$0.00";
}else{
return "$" + alloc.toFixed(2);
}
Can anyone help me refactor the #sum or #DbLookup to allow for empty values? Unfortunately I cannot define any new functions for this solution. The environment is locked down tightly. With a list of values of 5,5,"" and 5 I need a sum of 15.
I would try #Sum(#TextToNumber(#Trim(#Text(#DbLookup(...)))))
I would try
#Sum( #Transform( #Dblookup ( ....
If #DbLookup does not do what you need, you could always iterate over documents or view entries to build the sum.
The flow would be roughly like this:
1. Get a handle to the current database.
2. Get a handle to the "SubForms" view.
3a. Get a view entry collection using using getAllEntriesByKey() with MainFrmID as key, if a view column exists that displays the values you need.
--OR--
3b. Get a document collection using getAllDocumentsByKey() with MainFrmID as key, if no view column exists that displays the values you need.
4. Iterate over the collection to sum up values, using getColumnValues().get(columnNumber) to access the value from each view entry, or getItemValueDouble(fieldName) to access the value from each document.
That way you can easily detect null values and discard them.
I have a componet that updates an array on it's parent. Specifically, it takes additions, and creates an entirely new array that has been sorted, overwriting the original array.
var sortedUpdatedDomainNames = updatedProposedDomainNames.sort(sorts.domainName)
// even though we sort them, after setting the value, getting it returns the unsorted items
debugger;
Typing in the debugger here:
sortedUpdatedDomainNames
(4) ["example.com", "www.example.com", "swag.com", "www.swag.com"]
OK that works. The array items are sorted (using sorts.domainName which puts www immediately after parent domains)
await parentComponent.set('order.proposedDomainNames', sortedUpdatedDomainNames)
Here's the first issue: the DOM doesn't update poroperly, some items are duplicated in the DOM even though they're not duplicated in the data.
Running parentComponent.update fixes these duplications, however:
// Work around odd ractive bug where DOM doesn't update properly
// Trigger an update manually using .update()
// TODO: find proper fix!
await parentComponent.update('order.proposedDomainNames');
Her's the second issue: the values are now unsorted (well, they're sorted alphabetically now, which isn't what I want).
parentComponent.get('order.proposedDomainNames');
(4) ["example.com", "swag.com", "www.example.com", "www.swag.com"]
How can I overwrite an array using Ractive?
Please do not submit answers re: ractive.splice() etc - I do not know in advance the index where the data will be inserted, I simply wish to sort the entire array and update it.
Using the deep option for ractive.set() ensures the DOM updates to match the new array values - even though the array is a simple array of primitives.
await parentComponent.set('order.proposedDomainNames', sortedUpdatedDomainNames, { deep: true })
I also tried shuffle, which was suggested, but this does not work and the DOM is still inconsistent with the array value when using shuffle.
Though the issue is solved, I'm still interested in why deep was needed to make the DOM update correctly, so if you have your own answer to that, add it and I'l; accept it!
I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.
I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snippet of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".
I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here:
1. Perhaps this array is not being populated with any data at all.
2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?)
3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)
html:
<div>Florida Virginia</div>
<div>California Nevada</div>
<div>Ohio Indiana</div>
<div>New York Massachussetts</div>
<div>Oregon Washington</div>
js:
var region = $$('div');
document.writeln(region[2]);
document.writeln(region.indexOf('Ohio Indiana'));
Thanks for helping a js newbie figure out what is going on in the guts of this array.
$$ will return a list of DOM elements. If you are only interested in the text of those DOM nodes, then extract that bit out first. As #Dimitar pointed out in the comments, calling get on an object of Elements will return an array possibly by iterating over each element in the collection and getting the property in question.
var region = $$('div').get('text');
console.log(region[2]); // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2
Also use, console.log instead of document.writeln or document.write, reason being that calling this function will clear the entire document and replace it with whatever string was passed in.
See an example.