instantsearch.js with error in javascript console => RangeError: Invalid array length - algolia

I have this error on javascript console for a long time.
It is related with instantsearch.js and the paginator.
Can anyone help?
range.ts:18 Uncaught (in promise) RangeError: Invalid array length
at Ie (range.ts:18)
at t.value (Paginator.js:31)
at Object.render (connectPagination.js:147)
at index.ts:481
at Array.forEach (<anonymous>)
at Object.render (index.ts:472)
at InstantSearch.ts:510
at defer.ts:26
This error appear when the page load and I initialize the search instance.

Ok. Here is what you need to do.
Algolia Documentation
Code Sample
Finally. Inside your custom search client do this. Am using a sample computed property as my searchClient. Which will be cached thus not firing another request to Algolia.
search(requests) {
if (requests.every(({ params }) => !params.query)) {
// Here we have to do something else...
// Since the query is empty i.e. ""
return Promise.resolve({
results: requests.map(() => ({
// When an empty search is detected, a formatted response must be returned
// with atleast below properties.
// Otherwise;
// RangeError is generated if all other fields aren't provided.
hits: [],
nbHits: 0,
nbPages: 0,
page: 0,
facets: [],
processingTimeMS: 0,
hitsPerPage: 0,
exhaustiveNbHits: false,
query: "",
params: "",
})),
});
}
// Else query using provided input
return algoliaClient.search(requests);
},
};
}

Related

Ionic2 Native Storage storing/retrieving Arrays

I have an Ionic app in which I store an Array with Native-Storage.
This Array is an array of objects.
I stored it like this:
>>> array1: CertainType[] With at least 50 shuffled elements
this.nativeStorage.setItem('array1', { property: array1 })
.then(
() => { console.log('array1 stored') },
error => { console.log('array1 not Stored',error)
});
I retrieve the item like this:
this.nativeStorage.getItem('array1').then(
array1 => {
//On the Sucess of getting Array1 use it to create Array2
array2 = array1.splice(0,5); //<-- MY PROBLEM IS HERE
},
error => {
console.error('Error Getting Array', error);
}
);
I keep getting the Error of
I thought its because the process of storing and retrieving was messing with the type of the array, etc.
I tried to do casting:
..array1 as CertainType[]
-- EDITED>>
I tried stringfying and JSONparsing.
this.nativeStorage.setItem('array1', { property: JSON.stringify(array1)}).then(. . . .
array2 = JSON.parse(array1);
Throw this error:
ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
But i keep getting the same error on the splice().
If I not use the logic of storing, the code runs just fine.... Any clues. What am I missing? :/
Use JSON stringify before store in localStorage cause it will return a promise
just do this for example :
​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2);
The Ionic Native Storage Documentation confused me.
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
I sticked to the book and use almost equal code on my app. But that word "property" over there was breaking my floor.
The good contributor above me, insisted (thank god) on the use of JSON.stringify and JSON.parse to save and retrieve the data.
So I did, but kept getting errors. Then I realized: when I tried to retrieve the data, my Array was stored on an Object. Ok! But UNDER a p-r-o-p-e-r-y attribute..
If I did get my array1 using array1.property I would get what I was looking for.
In the end, just a little change will make it work like a clock:
this.nativeStorage.setItem('array1', JSON.stringfy(array)})
.then(. . .
this.storage.get('array').then( array1 => {
console.log(JSON.parse(array1));

setDataAsync() causes error when inserting into Lists with Word Online

I've recently noticed that when I attempt to set the value for a binding in Word Online for a selection of text that is a part of a bulleted list, numbered list, or multilevel list using the setDataAsync() method, I get the following error:
code: 5001 message: An internal error has occurred
Here is the code that I am trying to run (where bindingId is the binding ID of an already created binding within the document):
Office.select(`bindings#${bindingId}`).setDataAsync(
'test', { coercionType: 'text' }, (asyncResult) => {
if (asyncResult.status === 'failed') {
console.error(asyncResult.error.message);
}
console.log('success');
}
);
The way to reproduce this is by creating a numbered or bulleted list in a document in Word Online, and select some text that is part of one of the bullets or numbered items. Then create a binding for that selection using this code:
Office.context.document.bindings.addFromSelectionAsync(
'text', (asyncResult) => {
if (asyncResult.status === 'succeeded') {
console.log('success');
} else {
console.error('failed');
}
}
);
After the binding is created, you can try to set the binding's value to something using the setDataAsync() code from above. This will generate the An internal error has occurred error.
Thanks in advance for any insight!

Meteor-Mongo: Error handling for findone

I am trying to handle errors using findOne in meteor-mongo.
From this stackoverflow question, it appears that I should be able to handle errors by doing collection.findOne({query}, function(err, result){ <handleError> }, but doing so results in an errormessage:
"Match error: Failed Match.OneOf, Match.Maybe or Match.Optional validation"
The following code works:
export default createContainer((props) => {
let theID = props.params.theID;
Meteor.subscribe('thePubSub');
return {
x: theData.findOne({_id: theID}),
};
}, App);
The following code does not:
export default createContainer((props) => {
let theID = props.params.theID;
Meteor.subscribe('thePubSub');
return {
x: theData.findOne({_id: theID}, function(err,result){
if(!result){
return {}
};
}),
};
}, App);
What am I doing wrong and how should I be resolving this error? Is this a meteor specific error?
Any help is greatly appreciated!
What kind of error are you exactly trying to handle with your callback?
Meteor's findOne is different from node's mongodb driver's findOne that the post you link to uses.
The expected signature is:
collection.findOne([selector], [options])
There is no callback involved, since the method runs synchronously (but is reactive).
If you want to return a default value when the document is not found, you can simply use a JS logical OR:
// Provide an alternative value on the right that will be used
// if the left one is falsy.
theData.findOne({_id: theID}) || {};
A more rigorous approach would be to compare its type with
typeof queryResult === 'undefined'
Note that if theData collection is fed by the above subscription Meteor.subscribe('thePubSub'), I doubt Meteor will have time to populate the collection on the client by the time you query it…

How to get a better error message from Meteor in the case of an invalid DB update on a 'unique' indexed field?

I've set a unique index on one of my Meteor.users fields:
Meteor.startup(function() {
Meteor.users._ensureIndex('profile.uri', {unique: 1, sparse: 1});
});
I'm allowing users to edit this field via a front-end form.
When they attempt to update it to something already taken by another user, the app - as it should - throws an error and prevents the update.
However, the error I'm getting is just a blank 500 Internal server error:
M…r.m…e.errorClass {error: 500, reason: "Internal server error",
details: undefined, message: "Internal server error [500]", errorType:
"Meteor.Error"}
Which… isn't hugely useful for client-side error reporting.
How can I get Meteor to return a more precise error message so that I can appropriately interpret the cause of the error and report it to the user?
Naturally if I apply an error message specific to that error ("URI already taken") to the 500 response then it'll show for any 500 error, which could end up causing confusion if something else is causing it.
There may be one temporary solution. Update through a method, and check in the body of that method if the specific field already exists in the collection.
I guess you could also do that in a update allowing hook.
Yes, it is doing again what is already done by the DB (except the DB is probably doing it better).
I can't see any other solution to have the right error message.
Meteor.methods({
updateProfileUri : function(newUri) {
if(!this.userId) {
throw new Meteor.Error('user not signed-in');
}
check(newUri, String);
//If another user already uses this URI
if( Meteor.users.findOne({ _id: { $ne: this.userId }, 'profile.uri' : uri }) ) {
throw new Meteor.Error('uri already taken');
}
updateUriOfUser(this.userId, newUri);
}
});

How can I access a date typed field from an ExtJS JSonStore?

I've been trying to retrieve a date value and an integer value from the database, using the following code:
var l_alsChampsMois, l_stoDonneesMois;
try {
l_alsChampsMois = [
{name: "date_mois", type: "date", dateFormat: "Y-m-d"},
{name: "indice", type: "integer"}
];
l_stoDonneesMois = new Ext.data.JsonStore({
fields: l_alsChampsMois,
autoLoad: false,
proxy: {
type: "ajax",
url: "/commun/req_sql/req_ind_per_mois.php",
reader: {
type: "json",
root: "rows"
},
// some configs to use jsFiddle echo service (you will remove them)
actionMethods: {
read: "POST"
},
extraParams: {
key:"test"
}
},
listeners: {
load: function(objStore, alsLignes, blnOk, objOptions) {
window.alert("Mois fin : " + objStore.getAt(0).get("date_mois"));
}
}
});
l_stoDonneesMois.load({params: {
p_idsoc: l_strIdSociete,
p_mois: l_datDebut.getMonth() + 1,
// getMonth renvoie 0 pour janvier, etc.
p_annee: l_datDebut.getFullYear(),
p_debut: 1,
p_etape: 1
}
});
with l_strIdSociete and l_datDebut being variables previously assigned and /commun/req_sql/req_ind_per_mois.php the PHP page that retrieves the data and converts it to JSON.
It seems to work fine (indeed, Firebug tells me the load does retrieve a data structure with "date_mois" and "indice" containing the values I expect them to), only the window.alert returns undefined. If I replace "date_mois" with "indice", it returns the expected value for "indice".
I've tried to use objStore.getAt(0).getData()["date_mois"], to no avail.
My only clue about this is that "date_mois" in the data structure shown by Firebug is an Object, but even so it shouldn't be undefined, now should it? I looked up http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Field-cfg-type that wasn't exactly forthcoming with straight answers.
So what did I do wrong there?
If you need current time you can use php time function(note: it returns seconds, JS uses milliseconds), in another case you need to convert by mktime function.