In pusher.js file, xhr.onreadystatechange is getting called multiple times - reactjs

I am using pusher to add realtime updates feature to my react app. When a user updates a list item, The other user who is viewing it will see the updates in realtime. Recently I am facing some performance issues. Where page becomes unresponsive or laggy. After I did some debugging, I found this in the chrome console.
[Violation] 'readystatechange' handler took <N>ms
Then when I further dug into the issue. I see this function xhr.onreadystatechange = xhr.onprogress from pusher.js is getting called multiple times. Here is the whole piece of code where this function us residing
var http_xhr_request_hooks = {
getRequest: function (socket) {
var Constructor = runtime.getXHRAPI();
var xhr = new Constructor();
xhr.onreadystatechange = xhr.onprogress = function () {
switch (xhr.readyState) {
case 3:
if (xhr.responseText && xhr.responseText.length > 0) {
socket.onChunk(xhr.status, xhr.responseText);
}
break;
case 4:
if (xhr.responseText && xhr.responseText.length > 0) {
socket.onChunk(xhr.status, xhr.responseText);
}
socket.emit('finished', xhr.status);
socket.close();
break;
}
};
return xhr;
},
abortRequest: function (xhr) {
xhr.onreadystatechange = null;
xhr.abort();
}
};
I am not able to figure out why xhr.onreadystatechange = xhr.onprogress is getting called multiple times. Can someone please help me with this?

Related

lwc - how to call a function from within an lwc callback

Havent been able to reconcile this challenge to the docs :/ Hoping someone can point out to me why when this lwc renders (successfully) and it receives an event via its empApi subscription it throws a 'handleGoNext is not defined' runtime error. I appreciate the function is not visible, but I'm not able to construct things such that a resulting function call is able to be made successfully. Calling this.handleGoNext() doesnt work either. Any pointers would be most appreciated!
handleGoNext(){
// *** this is the logic Im hoping to call ***
};
// Initializes the component
connectedCallback() {
if(this.subscription = {}){
// Callback invoked whenever a new event message is received
const messageCallback = function (response) {
handleGoNext(); // *** THIS IS THE CALL THAT BREAKS THINGS ***
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then((response) => {
// Response contains the subscription information on subscribe call
console.log(
'Subscription request sent to: ',
JSON.stringify(response.channel)
);
this.subscription = response;
});
}
}
what happens when you do subscribe(this.channelName, -1, this.handleGoNext)?
Here's my function from around Easter time, didn't check recently if it still works.
isSubscribed = false;
subscription = {};
replayId;
#track data = [];
subscribe(id) {
const handleMessage = (response) => {
let val = Object.assign({}, response.data.event, response.data.payload);
this.replayId = Math.max(this.replayId ?? 0, val.replayId);
/* do not use this.data.push(val);
it doesn't play well with datatable. Use the spread operator or JSON.parse/JSON.stringify trick.
Plus we want new rows to be added on top of the list.`
*/
this.data = [val, ...this.data];
};
subscribe(this.channel, id, handleMessage).then((response) => {
this.subscription = response;
this.isSubscribed = true;
});
}

How does Meteor methods return results?

I am using meteor/react for learning facebook graph api.
I want to access users' post on facebook timeline and display them on screen. How can that be done?
With the guidance of the solution provided here [How to perform common FB actions using Meteor?. I have tried the following code: server.js
Meteor.methods({
'seePost' : function(){
var graph=Npm.require('fbgraph');
if(Meteor.user().services.facebook.accessToken){
graph.setAccessToken(Meteor.user().services.facebook.accessToken);
var future = new Future();
var onComplete = future.resolver();
graph.get('/me/feed',function(err,result) {
console.log(result);
return onComplete(err,result);
})
Future.wait(future);
}
else{
return false;
}
}
});
client side code :
Meteor.call("seePost", function(err,result) {
if(err) console.log("error" , err);
else console.log("RES", result);
});
I expect the result displayed in the client side console since I want to show the users the posts on his/er timeline, But I get following output :
RES, undefined
You can do it using await and Meteor.callAsync
Basically the client code waits for the call to complete, and gives you the returned data
const result = await Meteor.callAsync("seePost");
Errors should be handled with a try..catch block
If you use fibers/future, you need to return something with "future".
const future = new Future();
// some code getting result or something
future.return(something);
return future.wait();
this will return something in the callback from client call.
try this code, when you're using fibers you need to "wait" for the response
Meteor.methods({
'seePost': function () {
var graph = Npm.require('fbgraph');
if (Meteor.user().services.facebook.accessToken) {
graph.setAccessToken(Meteor.user().services.facebook.accessToken);
var future = new Future();
var onComplete = future.resolver();
graph.get('/me/feed', function (err, result) {
console.log(result);
if (err) {
return future.return(false);
} else {
return future.return(result);
}
})
return future.wait();
}
return false;
}
});

AngularJS $.post code runs after rest code

I have created following function in AngularJS
var enq_dt = new Date();
$.post("/api/EMSAPI/EnquiryDetails?enq_no="+o_enq_no, null, function (returnedData) {
enq_dt = returnedData["D_O_O"];
console.log("Loading Post Block");
console.log(enq_dt);
});
console.log("Loading General Block ");
console.log(enq_dt);
$scope.CurrentQuotation = {
EnquiryNo:o_enq_no,
EnquiryDate: enq_dt,
QuotationBy:"TEST"
};
I am getting following result in console window.
Loading General Block
2010-11-26T00:00:00
Loading Post Block
2010-12-12T00:00:00
I want to Load Post block first and after that I want to run General Block.
What I am missing (I am new to Angular) ?
Thanks in advance.
I suggest you Google the word "asynchronous". In JavaScript, things like HTTP requests are almost always asynchronous.
To get your general code to run after the post, call it with .then():
function generalCode() {
console.log("Loading General Block ");
console.log(enq_dt);
$scope.CurrentQuotation = {
EnquiryNo:o_enq_no,
EnquiryDate: enq_dt,
QuotationBy:"TEST"
};
}
var enq_dt = new Date();
$.post("/api/EMSAPI/EnquiryDetails?enq_no="+o_enq_no, null)
.then(function (returnedData) {
enq_dt = returnedData["D_O_O"];
console.log("Loading Post Block");
console.log(enq_dt);
})
.then(generalCode);

Function stops to work when $http is inside it

I've got a pretty odd issue if I ask myself.
Currently I've got a function in my view which is something like this:
<h3 ng-click="{{ vm.open(item.info) }}"> {{ item.title }} </h3>
and a function in my controller looking like this:
open = (url) => {
console.log(url);
}
This function works as intended it writes out the slug of the item from the view. But the issue comes when I try to add my API service or a simple $http.get() call. It seems to break the entire function because if I add this to the function:
open = (url) => {
console.log(url);
result.getOpportunity(url).then(result => {
res = result.data;
var modal = res.title;
console.log(modal);
});
}
Nothing gets printed out in the console. not even the first console.log() that worked so pretty just seconds ago.
Can anyone tell me what is going on? I don't get any error in either console or terminal but something do seem to be broken somewhere.
Worth mentioning is that I'm using an yeoman generator called Angular fullstack which uses Babel.
If I look into my gulp serve:ed .controller.js file that when I use the function that works. the single console.log line my file contains this:
this.open = function (url) {
console.log(url);
};
and when I use the longer function which doesn't work this is in the ouputted controller.js:
on the line where the function that works was this is now: _initialiseProps.call(this); and later on this function:
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.open = function (url) {
console.log(url);
_this2.result.getOpportunity(url).then(function (result) {
res = result.data;
var modal = res.title;
console.log(modal);
});
};
};
so Babel rewrites pretty much. but the most peculiar thing I noticed was that if I call _initialiseProps.call(this); explicit via the console I get returned undefined which do make some sense because the function _intiliaseProps() function does not contain a function called call()
but when I call _initialiseProps(this); from the console I get an error returned with this:
post.controller.js:29 Uncaught TypeError: Cannot set property '_checkURLforHTTP' of undefined(…)
Which is kinda funny or i dont know.. tearing my hair right now. Anyway, the _checkURLforHTTP function contains this in the code before babel had it's thing going:
_checkURLforHTTP = (img) => {
if (img.indexOf('http://') > -1 || img.indexOf('https://') > -1 ) {
return 'url("' + img + '")';
} else {
return 'url("http://HARDCODED-URL-HERE' + img + '")';
}
};
and the same function in the babel-processed file is the following:
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this._checkURLforHTTP = function (img) {
if (img.indexOf('http://') > -1 || img.indexOf('https://') > -1) {
return 'url("' + img + '")';
} else {
return 'url("https://HARDCODED-URL-HERE/' + img + '")';
}
};
};
Obviously it is something i'm not doing right, but i dont seem to understand what it is im doing wrong. I think I've managed to break it down into a click function in the view using $http.get();

Protractor : Error : Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

My E2E testing is to fill some details in a page, click a button to go to the next page and verify whether we reached the next page.Now I am able to move to the next page and scroll down but after that I couldn't select an element based on id, name or css it fails with the above error.
Why do we get "timeout Aysnc callback was not invoked" error ?
I have seen so many questions asking for same error but none of the answers is working in my case.PFB the code.
beforeEach(() => {
browser.manage().window().setSize(BROWSER_WIDTH, BROWSER_HEIGHT);
browser.get('index.html#/banking');
bankingDetails = require('./banking.page');
});
fit('should navigate to check panel for source type = saving and one ' +
'savings checkbox was selected', () => {
var checkPanelDetails = require('./check.page');
bankingDetails.fillBankingDetails(true, true);
bankingDetails.bankingWeiterButton.click();
browser.executeScript('window.scrollTo(0, 700);');
var isPresent = browser.wait(function () {
return checkPanelDetails.isVisible();
});
expect(isPresent).toBeTruthy();
});
check.page
var CheckPanel = function () {
this.checkPanel = element(by.name('check.confirm'));
this.isVisible = function () {
return this.checkPanel.isPresent();
};
};
module.exports = new CheckPanel();
Note:
I am using jasmine(2.4.1) and protractor(2.3.0)
Here is a link from jasmine Asynchronous_Support that help me understand time out problems. Hope that can help you,
describe("long asynchronous specs", function() {
beforeEach(function(done) {
done();
}, 10000);
});

Resources