winjs.xhr and function call in winjs - microsoft-metro

Scenario: I am trying to call a webservice which returns the results in json, the logic should be very straight forward.
I call a webservice url in WinJS.xhr() add a then function to process the result, here i am trying to bind it to a list.
I am using the below but i am not getting anything displayed what am i doing wrong here?
Can some one tell me how to call a winjs.xhr() from a function and return some object which i can bind as i am trying below?
function getData() {
return WinJS.xhr({ url: "http://search.twitter.com/search.json?q=%23windows8&rpp=10" })
}
function myFunc() {
getData().then(function (xhr) {
var jsondata = JSON.parse(xhr.responseText)
return jsondata;
// ...do something with the data when it arrives...
}, function (err) {
// ...do something with the error
});
}
var dataList = new WinJS.Binding.List(myFunc());
//var dataList = new WinJS.Binding.List(dataArray);
var publicMembers =
{
itemList: dataList
};
WinJS.Namespace.define("DataExample", publicMembers);

The ctor for WinJS.Binding.List accepts a list or array as the initial contents of the list. Your myFunc() will return nothing. You can set up an empty list using
var dataList = new WinJS.Binding.List()
and export it as you currently do.
Then, in myFunc(), placed below the dataList declaration, you can just add items to the list. For example, assuming that jsondata parses into an array:
function myFunc() {
getData().then(function (xhr) {
var jsondata = JSON.parse(xhr.responseText)
jsondata.forEach(function(entry) { dataList.push(entry); });
}, function (err) {
// ...do something with the error
});
}
Edit: I also assume you have bound dataList.dataSource to the itemDataSource of a WinJS.UI.ListView and set a matching itemTemplate property or render function.

Related

How to get data from react query "useQuery" hook in a specific type

When we get data from useQuery hook, I need to parse the data a specific type before it return to user. I want data which return from useQuery hook should be of "MyType" using the parsing function i created below. I am unable to find method to use my parsing function. Is there any way to do it? I don't want to rely on schema structure for data type.
type MyType = {
id: number;
//some more properties
}
function parseData(arr: any[]): MyType[]{
return arr.map((obj, index)=>{
return {
id: arr.id,
//some more properties
}
})
}
const {data} = await useQuery('fetchMyData', async ()=>{
return await axios.get('https://fake-domain.com')
}
)
I would take the response from the api and transform it inside the queryFn, before you return it to react-query. Whatever you return winds up in the query cache, so:
const { data } = await useQuery('fetchMyData', async () => {
const response = await axios.get('https://fake-domain.com')
return parseData(response.data)
}
)
data returned from useQuery should then be of type MyType[] | undefined
There are a bunch of other options to do data transformation as well, and I've written about them here:
https://tkdodo.eu/blog/react-query-data-transformations
I think you should create your own hook and perform normalisation there:
const useParseData = () => {
const { data } = await useQuery('fetchMyData', async () => {
return await axios.get('https://fake-domain.com')
}
return parseData(data)
}
And where you need this data you could just call const parsedData = useParseData()

Get data from subscribe in Ionic

I'm having difficulty getting data with subscribe in the constructor of an Ionic page, basically I need to do the subscribe to get a list and show to the user, but I get undefinied
In my constructor, I do this:
this.getUser(this.auth.currentUser().uid);
console.log(this.user);
My getUser():
getUser(uid) {
const self = this;
this.auth.getUserData(uid).subscribe(function(doc) {
if (doc.exists) {
self.user = doc.data();
} else {
console.log("No such document!");
}
});
};
But, when i call other function with button, i get the data:
userf(){
console.log(this.user);
}
Obs: I use Firestore
The reason it gives you undefined is because your method “getUser” is async and when you call console.log the user value is not yet obtained.
So you should access user value inside your getUser method after it is received.
Now also you are trying to pass “this” into the getUser method with const. start using fat arrow functions which do not create their own scope (this):
getUser(uid) {
this.auth.getUserData(uid).subscribe((doc) => {
if (doc.exists) {
this.user = doc.data();
} else {
console.log("No such document!");
}
});
};

Is it possible to locate subelements in protractor's .map?

Is it possible to locate sub-elements in protractor's .map?
I'm trying to modify example code from here to parse ToDo items into a data structure.
describe('angularjs homepage todo list', function() {
it('should add a todo', function() {
browser.get('https://angularjs.org');
element(by.model('todoList.todoText')).sendKeys('write first protractor test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todoList.todos'));
var todoStruct = todoList.map(function(el) {
return {
checkbox: el.element(by.model('todo.done')),
label: el.element(by.tagName('span')).getText()
};
});
todoStruct.then(function(resolvedTodoStruct) {
expect(todoStruct.length).toEqual(3);
expect(todoStruct[2].label).toEqual('write first protractor test');
});
});
});
From what I've read, map is the right choice for this kind of task. But for some reason, as soon as I use .element inside .map, protractor freezes. :(
Why would it happen? Did I miss anything?
I found a couple of work-arounds for this, though, while not pretty, seem work fine.
For the getText(), I moved the process of getting the text out of the JSON and then save the variable in the returned JSON.
For the element, the workaround is to wrap the element in a function:
var todoList = element.all(by.repeater('todo in todoList.todos'));
var spanText;
var todoStruct = todoList.map(function(el, index) {
var spanText = el.element(by.tagName('span')).getText().then(function(t){
return t;
});
return {
checkbox: function(){
return todoList.get(this.index).element(by.model('todo.done'));
},
label: spanText
};
});
Then when you want to access the element at a later time, you access as a function:
todoStruct.checkbox().click();
Yes, we can get sub elements from a map in the following way
getRows() {
return this.element.all(by.css('.ag-row')).map((row, index) => {
return {
index: index,
title: row.element(by.css("[colid=\"title\"]")).getText(),
operationStatus: row.element(by.css("[colid=\"operation_status_enum\"]")).getText()
};
});
}
// You can print this in the following way
this.getRows().then((rows) => {
for (var i=0; i<rows.length; i++) {
console.log(rows[i].title);
console.log(rows[i].operationStatus);
}
});

sails.js the return object from service is undefined when using a find query

I created a service called AppService.
Its function getUserPostionOptions is supposed to return an object:
getUserPostionOptions: function (user) {
// PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
var positionDirectionsOptions = [1,2,3];
var positionLengthsOptions = [4,5,6];
var object = {
directions:positionDirectionsOptions,
lengths:positionLengthsOptions
};
return object;
// });
}
This works, in my controller positionOptions gets populated correctly:
var positionOptions = AppService.getUserPostionOptions(user);
However, when I uncomment the find query the item is found but the object returns undefined.
Thank in advance for your help
SailsJs ORM (and almost NodeJs database querying methods) uses non-blocking mechanism via callback function. So you have to change your code into:
getUserPostionOptions: function (user, callback) {
PositionOptions.findOne({id:'53f218deed17760200778cfe'}).exec(function (err, positionOptions) {
var positionDirectionsOptions = [1,2,3];
var positionLengthsOptions = [4,5,6];
var object = {
directions:positionDirectionsOptions,
lengths:positionLengthsOptions
};
callback(null, object); // null indicates that your method has no error
});
}
Then just use it:
AppService.getUserPostionOptions(user, function(err, options) {
if (!err) {
sails.log.info("Here is your received data:");
sails.log.info(options);
}
});

Mootools Class - Calling a function within a function

I'm learning Mootools classes at the moment and there's something that I can't seem to get my head around or find a decent example.
Basically, I need to be able to call a function within a different function of the same class; example below:
var Bob = new Class({
initialize: function () {
this.message = 'Hello';
},
someOther: function() {
this.message2 = 'Bob';
},
getMessage: function() {
return this.someOther();
},
});
window.addEvent('domready', function() {
var map = new Bob;
alert(map.getMessage());
});
From this code, I would have thought that the alert would produce 'Bob' which has been set in the function 'someOther' but it's outputting a undefined message.
Can anyone help or point out where I'm going wrong?
Thanks in advance,
er not quite.
someOther has no return value in itself, it's a setter. you invoke it and it will set this.message2 into the class but it returns nothing. methods should return this (the instance, so making it chainable) or a value, when a getter.
anyway, you can make it set the property and return it like so:
var Bob = new Class({
initialize: function() {
this.message = 'Hello';
},
someOther: function() {
return this.message2 = 'Bob'; //bad
},
getMessage: function() {
return this.someOther(); // why
},
});
window.addEvent('domready', function() {
var map = new Bob;
alert(map.getMessage());
alert(map.message2); // bob
});
though, semantically, you want to have 1 getter. .getMessage should just return this.message - you can write a different method that calls someOther and returns it.
have a look at this pattern for a getter/setter in a class context I wrote the other day:
http://fragged.org/using-overloadsetter-overloadgetter-to-make-flexible-functions-in-mootools_1451.html
etc etc. for more help, look at the keetology blogs or davidwalsh.name - or the mootorial - plenty of examples of class use and structure.
most key ones are listed here: https://stackoverflow.com/tags/mootools/info