I have a react native app which I input a value to TextInput, then onEndEditing I call axios.get inside a function GetSKUOPAttributes(). The onEndEditing is working. At debug mode everything is working fine, only doesn't work in release. I've put an alert to check if the onEndEditing was working and it is. Could someone help me to findout why it doesn't work at release? The var opNumber and selectedLine have value inside.
function GetSKUOPAttributes() {
alert('http://10.113.16.113:8082/api/skuattribute/find?OP=' + opNumber + '&line=' + selectedLine);
axios.get('http://10.113.16.113:8082/api/skuattribute/find?OP=' + opNumber + '&line=' + selectedLine, {
}).then(function (response) {
alert('Inside GetSKUOPAttributes');
var temp = [];
response.data.map(r => InsertSKUAttribute(r.id, r.attributE_DESCRIPTION, r.sku, r.value, r.status) ,console.log('INSIDE MAP'));
sleep(200);
GetLocalAttributes();
}).catch(error => {
console.log(error);
});
}
after a long week I've found out what was the problem. And it was this Starting with Android 9 (API level 28), cleartext support is disabled by default.
So after many searches, many updates. The fix was very very simple.
All I needed was to add the tag bellow to AndroidManifest.
android:usesCleartextTraffic="true"
I will let a link to the complete post if others, have the same issue.
https://freakycoder.com/react-native-notes-21-android-http-network-security-problem-fix-eeac4e1ea58b
Related
My ReactJS project displays a simple page consisting of a header section with project title, version and a few nav links, then a table of about 200 results as the main content of the page.
The initial page loads for everyone and the components appear as expected, but on page load (I believe this is when the useEffect hook kicks in) some users report the page becoming un-responsive and no matter how long it is left, it never finishes. This has been reported in both Chrome and Edge by 5 different users across a site of 200+ users, the majority have no issues despite running the exact same hardware and connection.
On page load, I expect the title, version and table contents (plus a few other variables) to be populated and automatically updated since these are in state, and for most users, this works as expected.
Below is my useEffect()
useEffect(() => {
// Update all initial values
fetchLastUpdated();
fetchVersion();
fetchUsername();
fetchUpcomingFilterOptions();
fetchLongCustomerNames();
fetchConfigs();
fetchUpcomingResults() // This will be displayed as rows
const job = document.getElementById("job")
if ( !!job ) {
job.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
submitForm()
}
});
}
// Find environment for API links: testing/pre-release, testing/QA, flx
const url = window.location.href
if ( url.includes('localhost') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/pre-release') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/QA') ) {
setEnvironment("testing/QA")
} else if ( url.includes('flx') ) {
setEnvironment("flx")
}
}, [])
Below an example of an API call from useEffect
const fetchConfigs = () => {
axios({
method: "get",
url: "http://myURL/" + environment + "/WITracker/public/api/myConfigs",
config: { headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "multipart/form-data"
}}
})
.then(function (response) {
setConfigs(response.data);
})
.catch(function (response) {
console.log("Failed to fetch configs!");
addNotification("Unable to fetch configs", "Retry in progress...")
})
}
When remote accessing the users with troubles loading the page, I asked that they each try the alternative browser: Chrome -> Edge or Edge -> Chrome and in each case this resolved the issue. I found this strange as I would have expected the same browser to be causing the same behaviour each time across the users.
I would like to make sure that the page reliably loads for all users regardless of their browser preference. I'm at a bit of a loss trying to find out why only some users are getting unresponsive errors so any possible solutions or suggestions of what to try are welcome!
Possible workaround?
I'm not sure that I have set up my useEffect the correct way using best practices. I'm thinking of adding a slight delay to the API calls, since the page loads the components without issue, and once the delay is up, to synchronously make each of the calls, giving the browser more of a chance to process the smaller chunks of work rather than all at once... please can somebody let me know their thoughts on this?
e.g. Something similar to the below theory?
useEffect(async () => {
// Some delay here, with loading screen
wait(1000) //custom function to wait?
// ...then, update all initial values
await fetchLastUpdated();
await fetchVersion();
await fetchUsername();
await fetchUpcomingFilterOptions();
await fetchLongCustomerNames();
await fetchConfigs();
await fetchUpcomingResults()
...
Thanks in advance
Let me explain the situation, I'm currently testing an AngularJS website with Protractor, I'm not developing it at all.
The problem is that, absolutely randomly the website is sometime not rendered. It's just blank with a different title :
If title is "VideoGame" -> then website is rendered
If title is "VideoGame-env-DEV" -> Then the website isn't rendered
No idea why and it's not my concern.
However, when testing with Protractor, it's obviously crashing.
So I wanted to bypass the problem with a temporary solution :
function specialRefreshFunction() {
cpt=0;
browser.get('https://blablabla');
browser.waitForAngular();
var title = browser.getTitle();
while (title != "VideoGame") {
cpt=cpt+1;
//sleep(1000);
//browser.sleep(1000);
browser.get('https://blablabla');
browser.waitForAngular();
//browser.navigate().refresh();
console.log("fail "+cpt);
}
console.log("Correct title " + title);}
My solution isn't working. I'm a total newbie with NodeJS & Protractor, so the code might be a nonsense.
W10 64bits
Latest Chromedriver
Protractor 5.4.2
NodeJS 10.15.0
Angular 6.1.10
Thank you !
You can go with browser.wait
let EC = protractor.ExpectedConditions;
browser.wait(
EC.presenceOf($('#some-element')),
10000,
'Element did not appear after route change'
).then(function() {}, function() {
browser.refresh();
});
In this particular example protractor will wait 10 sec for element #some-element to appear on the page. browser.wait returns a promise, so you can handle both cases - when element appear or element did not appear. Just put some specific selector instead of $('#some-element') that present on your page, by which you can consider page as loaded
Though, if you rely only on title value, you can use titleContains
var EC = protractor.ExpectedConditions;
// Waits for the title to contain 'foo'.
browser.wait(EC.titleContains('foo'), 5000);
Try to create a custom promise like that:
public vierifyPageTitle() {
return new Promise((resolve, reject) => {
const refreshUserData = setInterval(() => {
return browser.getTitle().then((title) => {
if (title === 'VideoGame') {
clearInterval(refreshUserData);
resolve(title);
}
}, (err) => {
browser.refresh();
reject(err);
});
}, 1000);
});
}
It's refreshing every 1000 ms if title is not equal to expected.
I created a new route from the react-starter-kit project and it does an async fetch of some data, then renders it, but a second later the page reloads with a message saying "Page not found - sorry but the page you're trying to view does not exist".
In the console I see - "Warning: Text content did not match. Server: "Balances" Client: "Page Not Found"
async function action() {
let bittrex = new ccxt.bittrex ({
'apiKey': '',
'secret': ''
})
try {
// fetch account balance from the exchange
let bittrexBalance = await bittrex.fetchBalance ()
/**** commenting above and uncommenting this block stops it from happening....
let bittrexBalance = {};
bittrexBalance.info= [];
let currency = {};
currency.Currency = "BTC";
currency.Value=999;
// output the result
bittrexBalance.info.push(currency);*/
console.log ('balance', bittrexBalance)
let balances = [];
balances.push(bittrexBalance)
return {
title: "Balances",
component: (
<Layout>
<Balances balances={balances} />
</Layout>
),
};
} catch (e) {
console.log('SOME sort of error', e);
}
Does anyone have any idea what this could be?
Edit to add, I realise now that if I disable Javascript everything works perfectly...
It seems to be running through the universal router twice. The first time
That's the only clue I've found so far... I don't understand why it's reloading the page once it has already loaded...
The Page not found error is coming from it going through :
catch (e) the second time... I suspect something is happening inside the ccxt library but that the problem is actually that it is called a second time because the page is somehow reloaded...
It seems you have to call await bittrex.loadProducts() before fetching your Balance.
Edit : Seems also that bittrex.loadProducts() has been renamed by bittrex.loadMarkets()
More info in this issue on github
Your server code reached exception, which turns into rejection of route, because action method returns undefined, so server will fall down through —
next routes will not fit and finally it reaches the not found route.
I have a test that clicks a button and redirects to a user dashboard. When this happens Webdriver returns:
javascript error: document unloaded while waiting for result.
To fix this I insert browser.sleep(2000) at the point where redirection occurs and assuming my CPU usage is low, this solves the issue. However, 2000 ms is arbitrary and slow. Is there something like browser.waitForAngular() that will wait for the angular to load on the redirected page before the expect(..)?
it('should create a new user', () => {
$signUp.click();
$email.sendKeys((new Date().getTime()) + '#.com');
$password.sendKeys('12345');
$submit.click();
browser.sleep(2000); // Need alternative to sleep...
// This doesn't do it...
// browser.sleep(1);
// browser.waitForAngular();
$body.evaluate('user')
.then((user) => {
expect(user).toBe(true);
});
});
do you think something like this could work for you? This will wait up to 10 seconds for the url to include the text 'pageTwo', or whatever you put in.
var nextPageButton = $('#nextPage');
nextPageButton.click().then(function(){
return browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /pageTwo/.test(url);
});
}, 10000);
};
Just stick in the regex of the url you are expecting.
Alternatively, you could wait for an element from the next page to appear as well:
var nextPageButton = $('#nextPage');
nextPageButton.click();
var elementFromSecondPage = $('#coolElement');
browser.wait(protractor.until.elementIsVisible(elementFromSecondPage), 5000, 'Error: Element did not display within 5 seconds');
When using .click, protractor will naturally wait for angular to finish the action attached to the click, such as changing the page. But, while the page change, you may still be needing something specific to be loaded, so the test fails before that part is available. Using this, it should wait for the click part to finish, then wait for the element to appear.
To expand on user2020347's answer:
Thanks that solved my issue. I wonder why this isn't a built in function. I'll be using this in many places to wait for browser navigation.
To make it more concise, I made a little helper:
Object.assign(global, {
waitUntilURLContains: string => {
let fn = () => {
return browser.driver.wait(() => {
return browser.driver.getCurrentUrl().then((url) => {
return url.includes(string);
});
}, waitDelay);
}
return fn.bind(null, string);
}
});
In my test:
$button.click().then(waitUntilURLContains('dashboard'));
keeping it very simple. I was also running into the same problem but was able to solve it using the following code :
page.setUsername(objectrepository.userdetails.useremail);
page.setPassword(objectrepository.userdetails.userpassword);
page.login().click();
**browser.wait(EC.visibilityOf(page.greetingMessageElement()), 5000);**
page.greetingMessageElement().getText()
.then(function (value){
expect(browser.getCurrentUrl()).toContain("#/mytickets");
});
I am trying to build an Angular project with Pusher using the angular-pusher wrapper. It's working well but I need to detect when the user loses internet briefly so that they can retrieve missed changes to data from my server.
It looks like the way to handle this is to reload the data on Pusher.connection.state('connected'...) but this does not seem to work with angular-pusher - I am receiving "Pusher.connection" is undefined.
Here is my code:
angular.module('respondersapp', ['doowb.angular-pusher']).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('Foooooooo')
.setOptions({});
}
]);
var ResponderController = function($scope, $http, Pusher) {
$scope.responders = [];
Pusher.subscribe('responders', 'status', function (item) {
// an item was updated. find it in our list and update it.
var found = false;
for (var i = 0; i < $scope.responders.length; i++) {
if ($scope.responders[i].id === item.id) {
found = true;
$scope.responders[i] = item;
break;
}
}
if (!found) {
$scope.responders.push(item);
}
});
Pusher.subscribe('responders', 'unavail', function(item) {
$scope.responders.splice($scope.responders.indexOf(item), 1);
});
var retrieveResponders = function () {
// get a list of responders from the api located at '/api/responders'
console.log('getting responders');
$http.get('/app/dashboard/avail-responders')
.success(function (responders) {
$scope.responders = responders;
});
};
$scope.updateItem = function (item) {
console.log('updating item');
$http.post('/api/responders', item);
};
// load the responders
retrieveResponders();
};
Under this setup how would I go about monitoring connection state? I'm basically trying to replicate the Firebase "catch up" functionality for spotty connections, Firebase was not working overall for me, too confusing trying to manage multiple data sets (not looking to replace back-end at all).
Thanks!
It looks like the Pusher dependency only exposes subscribe and unsubscribe. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L86
However, if you access the PusherService you get access to the Pusher instance (the one provided by the Pusher JS library) using PusherService.then. See:
https://github.com/doowb/angular-pusher/blob/gh-pages/angular-pusher.js#L91
I'm not sure why the PusherService provides a level of abstraction and why it doesn't just return the pusher instance. It's probably so that it can add some of the Angular specific functionality ($rootScope.$broadcast and $rootScope.$digest).
Maybe you can set the PusherService as a dependency and access the pusher instance using the following?
PusherService.then(function (pusher) {
var state = pusher.connection.state;
});
To clarify #leggetters answer, you might do something like:
app.controller("MyController", function(PusherService) {
PusherService.then(function(pusher) {
pusher.connection.bind("state_change", function(states) {
console.log("Pusher's state changed from %o to %o", states.previous, states.current);
});
});
});
Also note that pusher-js (which angular-pusher uses) has activityTimeout and pongTimeout configuration to tweak the connection state detection.
From my limited experiments, connection states can't be relied on. With the default values, you can go offline for many seconds and then back online without them being any the wiser.
Even if you lower the configuration values, someone could probably drop offline for just a millisecond and miss a message if they're unlucky.