Set Timeout not working in React Native - Debug JS Remotely - javascript

I drove myself nuts trying to figure out what the problem is with my code. I am building a React Native application and developing in the IOS Simulator after running run-ios. I enabled Debug JS Remotely so I can verify the condition of my tokens returned from the server.
I am attempting to build a simple service that will refresh my tokens using a setTimeout.
let sessionTimeout = null;
export const session = (response) => {
let tokens = response.tokens;
Store.set(tokens);
setSessionTimeout(tokens.access.expiresIn);
};
const setSessionTimeout = (duration) => {
let time = duration - 5000;
clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(() => {
console.log('settimeout called');
refreshToken();
}, 1000);
};
const refreshToken = () => {
let tokens = Store.get();
refresh(tokens)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
};
In the above code a began my initial test by hardcoding 1000 and it worked fine. It successfully made the call to my server. I then attempted to implement the proper time duration and found it does not work. Even by replacing the 1000 with 2000 causes it to fail and the call to the backend is never made.
I then tried using the following packages and got the same result:
react-native-timer
react-timer-mixin
After banging my head on the wall for two days and having another attempt on stack shot down because my issue could not be reproduced I disabled the Debug JS Remotely and everything works as expected.
However now I am wondering how I am supposed to debug the frontend portion of my application with out the use of this feature. If anyone has any ideas or advice on issues like this I would appreciate the feedback as this is my first React Native app.

Related

Unable to query or get any response from BscScan contract

The following code:
const { JsonRpcProvider } = require("#ethersproject/providers")
const { Contract } = require("ethers")
const { Wallet } = require("#ethersproject/wallet");
const abi = require('./abi.json');
const GLOBAL_CONFIG = {
PPV2_ADDRESS: "0x18B2A687610328590Bc8F2e5fEdDe3b582A49cdA",
PRIVATE_KEY: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
BSC_RPC: "https://bsc-mainnet.public.blastapi.io"
};
const signer = new Wallet(GLOBAL_CONFIG.PRIVATE_KEY, new JsonRpcProvider(GLOBAL_CONFIG.BSC_RPC));
const contract = new Contract(GLOBAL_CONFIG.PPV2_ADDRESS, abi, signer)
const predictionContract = contract.connect(
signer
)
predictionContract.on("StartRound", async (epoch) => {
console.log("\nStarted Epoch", epoch.toString())
});
It has been working perfectly for months. However, last night it stopped. No new builds/code changes on my end. I've been trying everything I can think of but nothing. The signer seems to bring back my wallet details ok. I can also see all the functions on the predictionContract but can't get it to return the current Epoch value etc. As you've probably already noticed, I'm not much of a coder, so any help in understanding this would be amazing.
After some more time thinking, I noticed that the contract seemed pretty busy and decided to try a different RPC (I'd already tried 3 before). Seems to be working now, but not exactly scientific. Is there any way to monitor the time requests take and where the lag is? I had a design idea to test a multiple of RPCs during initiation and then use the fastest / most reliable, but no idea where to start with that!

Can i send data after each second (reactive) from WKWebView to native in Swift

I am creating a View which displays a local webpage which also has styles and JavaScript using a WKWebView.
I want to send data every second from WebView using node js like this
const timerEventEmitter = new EventEmitter();
timerEventEmitter.emit("update");
let currentTime = 0;
// This will trigger the update event each passing second
setInterval(() => {
currentTime++;
timerEventEmitter.emit('update', currentTime);
}, 1000);
timerEventEmitter.on('update', (time) => {
console.log('Message Received from publisher');
console.log(`${time} seconds passed since the program started`);
});
Can i send the log
{time} seconds passed since the program started
to native ios app, or send data using react like this
You can use socket.io to have server pushing datas to webview application.
Take a look at the get started of socket.io website : https://socket.io/get-started/chat
Tell if you have questions.

How can I slow down readings I get from a QR Scanner?

this is my first post.
greetings to readers.
So Im fairly new to coding, and ive got this code implemented onto my frontend, a succesful scan sends a GET request to my python API to fetch data from database.. but this script scans qr code few times a second (not only that but it submits it too).
So my question is how could I slow it down a bit, lets say a timeout for 2 seconds after a succesful scan?
function onScanSuccess(decodedText, decodedResult) {
// Handle on success condition with the decoded text or result.
console.log(`Scan result: ${decodedText}`, decodedResult);
$('#search').val(decodedText);
$('#frm').submit();
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess);
});
edit: I havent said I didnt write this and I have no idea how to do timeouts in Typescript or Javascript and not even where.
Im thanking you for your time :)
This is taken directly from the html5QrcodeScanner example. On success, it will update the result, and if there's no new result scanned, it wont update the result
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, countResults = 0;
function onScanSuccess(decodedText, decodedResult) {
if (decodedText !== lastResult) {
++countResults;
lastResult = decodedText;
// Handle on success condition with the decoded message.
console.log(`Scan result ${decodedText}`, decodedResult);
}
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess);
but this wont stop your device from scanning, it just won't update the result as from my understanding of your question that would be sufficient, but if you want to stop the camera/ scanning process altogether after successful scan, you can go into a lil bit advanced part of the library
import {Html5Qrcode} from "html5-qrcode"
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.stop().then((ignore) => {
// QR Code scanning is stopped.
}).catch((err) => {
// Stop failed, handle it.
});
by doing this also means that you need to implement the whole process from Pro Mode, you can refer here for pro mode

ReactJS : How to detect network idle between XHR requests

I'm fairly new to the JS world and working with React JS. Couldn't find anything for the exact solution.
I want to implement an App level idle timer which would be activated when the user does not make any server request for a specific time period. The function should be triggered after X mins of the last XHR request irrespective of whether the user navigates between components or not.
For example - If user clicks on a button which calls an API and just plays around the screen without making another service call for X mins, the function should be triggered. At this stage, though user is not idle on the website, there's an idleness in the network activity. I want to detect this and perform some actions.
Also, would like to know the performance impact of the solution. Thanks!
Use PerformanceObserver to detect the fetch and then add/update timer using the setTimeout
let timer;
const observer = new PerformanceObserver((items) => {
items
.getEntries()
.filter(({ initiatorType }) => initiatorType === "fetch")
.forEach((entry) => {
console.log("Made fetch request", entry.name);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => console.log("(idle) After 2 sec"), 2000);
});
});
observer.observe({
entryTypes: ["resource"],
});
fetch("https://swapi.dev/api/planets/1/").then((res) => res.json());
setTimeout(
() => fetch("https://swapi.dev/api/planets/2/").then((res) => res.json()),
1000
);
setTimeout(
() => fetch("https://swapi.dev/api/planets/3/").then((res) => res.json()),
3000
);
The Network Information Api.
I'm not sure but you can try subtract downlink from downlinkMax.
But this Api is not well supported Can i use

Apify web scraper task not stable. Getting different results between runs minutes apart

I'm building a very simple scraper to get the 'now playing' info from an online radio station I like to listen too.
It's stored in a simple p element on their site:
data html location
Now using the standard apify/web-scraper I run into a strange issue. The scraping sometimes works, but sometimes doesn't using this code:
async function pageFunction(context) {
const { request, log, jQuery } = context;
const $ = jQuery;
const nowPlaying = $('p.js-playing-now').text();
return {
nowPlaying
};
}
If the scraper works I get this result:
[{"nowPlaying": "Hangover Hotline - hosted by Lamebrane"}]
But if it doesn't I get this:
[{"nowPlaying": ""}]
And there is only a 5 minute difference between the two scrapes. The website doesn't change, the data is always presented in the same way. I tried checking all the boxes to circumvent security and different mixes of options (Use Chrome, Use Stealth, Ignore SSL errors, Ignore CORS and CSP) but that doesn't seem to fix it unfortunately.
Scraping instable
Any suggestions on how I can get this scraping task to constantly return the data I need?
It would be great if you can attach the URL, it will help me to find out the problem.
With the information you provided, I guess that the data you want to are loaded asynchronously. You can use context.waitFor() function.
async function pageFunction(context) {
const { request, log, jQuery } = context;
const $ = jQuery;
await context.waitFor(() => !!$('p.js-playing-now').text());
const nowPlaying = $('p.js-playing-now').text();
return {
nowPlaying
};
}
You can pass the function to wait, and I will wait until the result of the function will be true. You can check the doc.

Categories

Resources