I need to display available WiFi network's list.
By using npm install react-native-wifi-reborn --save I can get the list but only in the log. How can I display the Wifi List as text from the console log.
I tried this code.
But got this error
Error: Exception in HostFunction: Malformed calls from JS: field sizes are different.
As per the docs,loadWifiList() returns Promise<Array<WifiEntry>>, so you should either use async/await or .then to access the result.
You could try something like this
const getWifiList = async() => {
let wifiList = await wifi.loadWifiList(); //wifiList will be Array<WifiEntry>
console.log('wifi list',wifiList);
}
Related
Expo React Native SDK Version: 46
Platforms: Android/iOS
Package concerned : Expo.Updates
Hello everyone, I want to programmatically check for new updates, without using the fallbackToCacheTimeout in app.json that will trigger the check of the new updates when the application is launched because like that I can't put a custom loading page.
So by doing this all by code as follow :
try{
const update = await Updates.checkForUpdateAsync();
if(update.isAvailable){
await Updates.fetchUpdateAsync();
await Updates.reloadAsync();
}else{}
}catch(err){}
But I want to be able to abort all those calls after a certain time (thus, the user that have a bad connection can use the app without waiting a very long time).
I check the documentation and I cannot found any method that allow this.
I dont't think it's possible to cancel a Promise for now in Javascript, or maybe any connection ?
Or does the "fallbackToCacheTimeout" value in the app.json will automatically apply to the fetch updates call of the Expo API?
Do someone have any idea how to do it ? :(
First of all I am assuming you have set updates.checkautomatically field to ON_ERROR_RECOVERY in app.json or app.config.js file. If not, please check the documentation. The reason why you need this is to avoid automatic updates which can also block your app on splash screen.
Updated Solution
Because of the limitation in javascript we can't cancel any external Promise (not created by us or when its reject method is not exposed to us). Also the function fetchUpdateAsync exposed to us is not a promise but rather contains fetch promise and returns its result.
So, here we have two options:
Cancel reloading the app to update after a timeout.
But note that updates will be fetched in background and stored on
the device. Next time whenever user restarts the app, update will
be installed. I think this is just fine as this approach doesn't
block anything for user and also there is a default timeout for http
request clients like fetch and axios so, request will error out in
case of poor/no internet connection.
Here is the code:
try {
const update = await Updates.checkForUpdateAsync();
if (update.isAvailable) {
const updateFetchPromise = Updates.fetchUpdateAsync();
const timeoutInMillis = 10000; // 10 seconds
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject("timedout"), timeoutInMillis))
// This will return only one Promise
Promise.race([updateFetchPromise, timeoutPromise])
.then(() => Updates.reloadAsync())
.catch((error) => {
if (error === 'timedout') {
// Here you can show some toast as well
console.log("Updates were not cancelled but reload is stopped.")
} else if (error === 'someKnownError') {
// Handle error
} else {
// Log error and/or show a toast message
}
})
} else {
// Perform some action when update is not available
}
} catch (err) {
// Handle error
}
Change the expo-updates package just for your app using a patch
Here you can return a cancel method with Updates.fetchUpdateAsync() and use it with setTimeout to cancel the fetch request. I won't be providing any code for this part but if you are curious I can definitely provide some help.
Please refer this section to understand use of fallbackToCacheTimeout in eas updates.
Old solution:
Now, for aborting or bypassing the promise i.e. Updates.fetchUpdateAsync in your case. You can basically throw an Error in setTimeout after whatever time duration you want, so that, catch block will be executed, bypassing the promises.
Here is the old code :
try{
const update = await Updates.checkForUpdateAsync();
if(update.isAvailable){
// Throw error after 10 seconds.
const timeout = setTimeout(() => { throw Error("Unable to fetch updates. Skipping..") }, 10000)
await Updates.fetchUpdateAsync();
// Just cancel the above timeout so, no error is thrown.
clearTimeout(timeout)
await Updates.reloadAsync();
}else{}
}catch(err){}
When I use fetch() method to make get request, it failed with "TypeError: Network request failed". It's weird that it sometimes failed but sometimes succeeded. I have tried the solution here: React Native fetch() Network Request Failed, but it didn't work for me. By the way, I am using Android.
This is my code :
try {
let url = "http://140.116.245.229:3000/GetCarsJson";
let data = await fetch(url);
let toJson = await data.json();
} catch(err) {
throw err;
}
This is the error message :
enter image description here
You should ensure your devices/simulator/emulator can connect to this endpoint
If you use Android emulator, you can refer this link How to connect to a local server from an android emulator?
I was trying to list all the files in a folder using rn fetch blob in react native. When i tried to list it i am getting an error saying
[Error: Attempt to get length of null array]
here is the below code I have tried to list the files.
try {
var TRACK_FOLDER = RNFetchBlob.fs.dirs.DownloadDir + '/BlabberApp/';
let files = await RNFetchBlob.fs.ls(TRACK_FOLDER)
console.log(files);
} catch (error) {
console.log(error);
}
Its working perfectly in system emulator and when i tested in real devices its force closing and throwing this error. I am pretty sure that i gave given storage permission for this but still I am getting this error.
Any help would be appreciable.
Thanks in advance :)
use this code ,I am using this to get the name of files in that specified folder and TRACK_FOLDER is path of the folder-
RNFetchBlob.fs.ls(TRACK_FOLDER).then(files => {
console.log(files);
}).catch(error => console.log(error))
Usually, this is a Storage Permission Error: You need to ask permission.
I am trying to send the verification code received by the user to confirm the signIn, I have the SMS_MFA enabled. However, I keep getting this error Unknown error, the response body from fetch is: undefined and thats all I get, there is nothing else to help me understand what the error is about. And everything else is working fine, I call signIn, signUp, confirmSignUp and resendSignUp, they all work fine. The problem is only with confirmSignIn and I have no idea what it could be, I already researched online, but had no success. Another strange thing that happens, when I enter the wrong code, it shows me the 'CodeMismatchException', but it fails with 'Unknown error' when code is the right one. PS: I already have cognito configured to work with SMS MFA
I'am having this problem in android and iOS. React native version 0.55.4 and aws-amplify version ^1.0.11
I have a file where a call all the Auth functions and export them
export const confirmSignIn = (cognitoUser, code) => Auth.confirmSignIn(cognitoUser, code, 'SMS_MFA');
Then I call that confirmSignIn function from a different file
confirmSignIn(cognitoUser, code).then((userSession) => {
console.log(userSession);
}).catch((error) => {
switch (error.name) {
case 'CodeMismatchException':
this.codeInput.clear();
break;
default:
console.log(error);
break;
}
});
I already tried upgrading aws-amplify version, but it didn't work, tried to do it with cognitoUser.sendMFACode() but didn't work either. I just keep getting Unknown error, the response body from fetch is: undefined
I also opened an issue in the aws-amplify repo.
Does anyone know what is the best way to catch all uncaught exception (globally) so that I can send a crash report back to the server? I don't seem to be able to find any information on the react native docs or on github.
You could possibly override the exception logging that React Native uses for development:
ErrorUtils.setGlobalHandler(function() {
// your handler here
});
https://github.com/facebook/react-native/blob/522fd33d6f3c8fb339b0dde35b05df34c1233306/Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js#L46
You may then need to write some Obj-C which you expose to JS, depending on your exact requirements.
This is how I'd do it:
Step 1: We intercept react-native error handler like so:
//intercept react-native error handling
if (ErrorUtils._globalHandler) {
this.defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler;
ErrorUtils.setGlobalHandler(this.wrapGlobalHandler); //feed errors directly to our wrapGlobalHandler function
}
Step 2: Now our wrapGlobalHandler gets called whenever theres an unhandled error. So do anything you want with the error within this function.
Then do something with the error:
async function wrapGlobalHandler(error, isFatal){
const stack = parseErrorStack(error);
//do anything with the error here
this.defaultHandler(error, isFatal); //after you're finished, call the defaultHandler so that react-native also gets the error
}
Full code here:
import stacktraceParser from 'stacktrace-parser';
const parseErrorStack = (error) => {
if (!error || !error.stack) {
return [];
}
return Array.isArray(error.stack) ? error.stack :
stacktraceParser.parse(error.stack);
};
// intercept react-native error handling
if (ErrorUtils._globalHandler) {
this.defaultHandler = (ErrorUtils.getGlobalHandler
&& ErrorUtils.getGlobalHandler())
|| ErrorUtils._globalHandler;
ErrorUtils.setGlobalHandler(this.wrapGlobalHandler); // feed errors directly to our wrapGlobalHandler function
}
async function wrapGlobalHandler(error, isFatal) {
const stack = parseErrorStack(error);
//do anything with the error here
this.defaultHandler(error, isFatal); //after you're finished, call the defaultHandler so that react-native also gets the error
}
Thats it!
You can try https://github.com/master-atul/react-native-exception-handler.
A react native module that lets you to register a global error handler that can capture fatal/non fatal uncaught exceptions. The module helps prevent abrupt crashing of RN Apps without a graceful message to the user.
There is a native way.
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:_scriptURL
moduleProvider:^{
id<RCTExceptionsManagerDelegate> customDelegate = ...
return #[[RCTExceptionsManager initWithDelegate:customDelegate];
}
launchOptions:nil];
Just put your report logic in the customDelegate.
There's now react-native-error-reporter, which pretty much does the trick in a very simple way:
npm i react-native-error-reporter --save
rnpm link
Then add this lines to your code:
import ErrorReporter from 'react-native-error-reporter';
ErrorReporter.init("vanson#vanportdev.com", "My App's Crash Report");
In case you're using Redux, you might wanna try redux-catch middleware.