Uncaught (in promise) Error: call revert exception when calling smart contract function - smartcontracts

I realise others have posted this error but not of the suggested fixes have worked.
Testing on localhost network
Uncaught (in promise) Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="fetchNftsForSale()", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.6.0)
My project is based from this https://dev.to/edge-and-node/building-scalable-full-stack-apps-on-ethereum-with-polygon-2cfb and code for this part is near identical
My issue deviates from others who have posted in that it works when the site is first loaded. It will call the fetchNftsForSale() method and return an empty array. No problem.
It's only after an nft has been minted and then going back to the page to display nfts for sale that the error occurs.
Doesn't make sense as the contract address is still the same
I've looked at the causes listed here but nothing stands out a being the cause. https://docs.ethers.io/v5/troubleshooting/errors/#help-CALL_EXCEPTION
Also this has been working previously and has only just stopped and I'm not sure what could have changed.
From what I can see, the provider is connected to the same network as like I said, the function call works when before signing transactions to create items.
I've created unit tests for minting, listing, buying and they all work.
I've also tried various different versions of Hardhat and ethers.js
Call to contract:
const loadProperties = async () => {
const provider = new ethers.providers.JsonRpcProvider()
const tokenContract = new ethers.Contract(nftaddress, NFT.abi, provider)
const marketContract = new ethers.Contract(nftmarketaddress, PropertyMarket.abi, provider)
const data = await marketContract.fetchPropertiesForSale()
Smart Contract:
function fetchNftsForSale() public view returns (MarketItem[] memory) {
uint itemCount = _tokenIds.current();
uint unsoldItemCount = _tokenIds.current() - _itemsSold.current();
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(this)) {
uint currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
Dependencies:
"dependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.4",
"#nomiclabs/hardhat-waffle": "^2.0.1",
"#openzeppelin/contracts": "^4.5.0",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"#testing-library/user-event": "^13.2.1",
"axios": "^0.24.0",
"chai": "^4.3.4",
"ethereum-waffle": "^3.4.0",
"ethers": "^5.6.1",
"hardhat": "^2.8.2",
"ipfs-http-client": "^55.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.1",
"react-scripts": "5.0.0",
"solc": "^0.8.12",

Related

I'm creating an erp connector for a company with google data studio, but I don't know how this process works

const cc = DataStudioApp.createCommunityConnector();
function getAuthType() {
return cc.newAuthTypeResponse()
.setAuthType(cc.AuthType.USER_TOKEN)
.setHelpUrl('https://api.sigecloud.com.br/swagger/ui/index#/')
.build();
}
function resetAuth() {
var userTokenProperties = PropertiesService.getUserProperties();
userTokenProperties.deleteProperty('dscc.username');
userTokenProperties.deleteProperty('dscc.password');
}
function isAuthValid() {
var userProperties = PropertiesService.getUserProperties();
var userName = userProperties.getProperty('dscc.username');
var token = userProperties.getProperty('dscc.token');
var res = UrlFetchApp.fetch(`https://api.sigecloud.com.br/request/Pedidos/GetTodosPedidos&Authorization-Token${token}&User=${userName}&page=12&App=API APP`, { 'muteHttpExceptions': true });
return res.getResponseCode() == 200;
}
function getConfig() {
}
function getSchema() {
}
function getData() {
}
This is Manifest:
{
"timeZone": "America/Sao_Paulo",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"dataStudio":{
"name": "Two Dogs Connector with Sige",
"description": "The unofficial conecctor to acess Sige Data",
"company": "Mateus C Rocha",
"logoUrl": "https://images.sympla.com.br/62ea7b9d69ec5.png",
"addOnUrl": "https://twodogs.com/br/quem-somos/",
"supportUrl": "https://twodogs.com/br/quem-somos/"
}
}
This error appears when I add the implementation ID generated when I select the test implementation option, in the google script
My api needs to receive: Page, user(constant value), token(constant value) and App(constant value)...
I don't know how it works, but I was hoping it wouldn't show errors, as I followed the documentation https://developers.google.com/looker-studio/connector/get-started

Getting a Runtime error when passing an Integer into a Solidity function that take uint256 as parameter

My Solidity smart contract has this function:
function getPlayerAddress(uint256 index) public view returns(address) {
return s_players[index];
}
And I am trying to pass an Integer as parameter via my frontend React application.
This is what the State looks like:
const [playerIndex, setPlayerIndex] = useState(0)
This is the function where I am trying to pass the value:
const updatePlayer = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const contract = new ethers.Contract(stallionRunAddress, abi, provider)
**const newPlayer = await contract.getPlayerAddress(playerIndex)**
const newPlayerLevelBI = await contract.ownedHorseLevel(newPlayer)
const newPlayerLevel = parseInt(newPlayerLevelBI)
const newPlayerHorseArr = await contract.ownedHorseName(newPlayer)
const newPlayerHorse = newPlayerHorseArr[0].toString()
setPlayers(...players, {address: newPlayer, level: newPlayerLevel, horse: newPlayerHorse})
}
I get this error:
Unhandled Runtime Error
Error: call revert exception; VM Exception while processing transaction: reverted with panic code 50 [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getPlayerAddress(uint256)", data="0x4e487b710000000000000000000000000000000000000000000000000000000000000032", errorArgs=[{"type":"BigNumber","hex":"0x32"}], errorName="Panic", errorSignature="Panic(uint256)", reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)
I have tried passing it as a value with 18 decimals (wei format):
playerIndex * 1e18
But it still doesn't fix the error. How do i fix this?
Solidity uint256 integers can be passed by web3js should be BigNumber instead of js integers. Also you can use string as well.

Appcelerator Device Token converted to FCM token

I have an old app developed with Appcelerator - Titanium SDK using FCM Push notifications.
The device token that I get on the device is:
"baf48325219887fdb5929ac5d9495d8897a48f0b77a1c9c23131097e51dc1234"
Because Appcelerator is deprecated, I want to know how to get the FCM token so I can still notify the devices even if Appcelerator has been deprecated.
** UPDATE **
This is the code for getting the deviceToken:
exports.requestDeviceToken = function() {
if (Ti.Platform.model.indexOf('Simulator') !== -1 || Ti.Platform.model.indexOf('Emulator') !== -1) {
return;
}
var params = {
callback:pushNotificationCallback,
success:deviceTokenSuccess,
error: deviceTokenError,
};
var types = [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
];
if (Ti.Platform.name == 'android') {
var CloudPush = require('ti.cloudpush');
// Initialize the module
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError,
});
CloudPush.addEventListener('callback', pushNotificationCallback);
}
else {
if (Ti.Platform.name != "android" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
Ti.API.info('registering push notifications iOS > 8');
Ti.Network.registerForPushNotifications(params);
Ti.App.iOS.registerUserNotificationSettings({types:types});
}
else {
params.types = types;
Ti.Network.registerForPushNotifications(params);
}
}
};
Any clue?
There is https://github.com/hansemannn/titanium-firebase-cloud-messaging available since 2017 that you can use to connect your app to FCM. Using it for years and it's working without any issue.
Transfering an existing app takes around 30mins.
...
if (OS_IOS) {
const FirebaseCore = require('firebase.core');
fc.configure();
}
const FirebaseCloudMessaging = require('firebase.cloudmessaging');
if (OS_ANDROID) {
FirebaseCloudMessaging.registerForPushNotifications();
}
...
as a short example. A fulll example with connection to the Android channels, how to get the token (iOS and Android) is available in the repo at https://github.com/hansemannn/titanium-firebase-cloud-messaging#example

React Native build error: Text must not be null or empty

My Jenkins build has given me the following error:
13:18:22 FAILURE: Build failed with an exception.
13:18:22
13:18:22 * Where:
13:18:22 Script '/Users/abcd/Jenkins/Jenkins-Workspaces/ABCD/ABCDL/node_modules/#react-native-community/cli-platform-android/native_modules.gradle' line: 190
13:18:22
13:18:22 * What went wrong:
13:18:22 A problem occurred evaluating settings 'AppName'.
13:18:22 > Text must not be null or empty
13:18:22
It seems the problem is with the #react-native-community/cli-platform node module, but reading over this closed issue:
https://github.com/facebook/react-native/issues/25479
its unclear to me what exactly is the proposed and final solution to this.
There is a recommendation on a fix that is more straightforward in this react-native issue:
https://github.com/facebook/react-native/issues/25822
but my error is not complaining about that line.
As far as installing #react-native-community/cli I believe I already have it inside my package-lock.json file:
"react-native": {
"version": "0.60.4",
"resolved": "https://registry.npmjs.org/react-native/-/react-native-0.60.4.tgz",
"integrity": "sha512-WE41lbGQjnzM9srIFtMDtMJkQAvk95iZwuFvAxl68s80bkYa7Ou9sGFHpeYIV6cY8yHtheCSo5q6YMxhdfkdOw==",
"requires": {
"#babel/runtime": "^7.0.0",
"#react-native-community/cli": "^2.0.1",
"#react-native-community/cli-platform-android": "^2.0.1",
"#react-native-community/cli-platform-ios": "^2.0.1",
Others mentioned something about app/build.gradle, here is the relevant part of mine:
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Mention was also made of android/settings.gradle, this one is mine:
rootProject.name = 'NFIBEngage'
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':appcenter-crashes'
project(':appcenter-crashes').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-crashes/android')
include ':appcenter-analytics'
project(':appcenter-analytics').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter-analytics/android')
include ':appcenter'
project(':appcenter').projectDir = new File(rootProject.projectDir, '../node_modules/appcenter/android')
include ':react-native-webview'
project(':react-native-webview').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview/android')
apply from: file("../node_modules/#react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
From what I have gathered here:
https://react-native-community.github.io/upgrade-helper/?from=0.53.3&to=0.60.4
The above files are correct.
So what exactly is wrong here and how do I fix it?
In terms of node_modules/#react-native-community/cli-platform-android/native_modules.gradle line 190 is this one:
def json = new JsonSlurper().parseText(reactNativeConfigOutput)
Could the problem be with how I wrote index.js file:
/**
* #format
*/
import { AppRegistry } from "react-native";
// old config code
import KeyboardManager from "react-native-keyboard-manager";
// old config code ^^^
import NFIBEngage from "./App";
import { name as appName } from "./app.json";
// old config code
import { Sentry } from "react-native-sentry";
Sentry.config(
"https://asdf#sentry.io/123456677"
).install();
KeyboardManager.setToolbarPreviousNextButtonEnable(true);
// old config code ^^^
AppRegistry.registerComponent("NFIBEngage", () => NFIBEngage);
Is AppRegistry.registerComponent() written correctly?
I ran the Jenkins script locally, which I believe is this script right here:
import fs from "fs-extra";
import eachSeries from "async/eachSeries";
import { exec } from "child_process";
import { androidDirectory } from "../../app.json";
import { resolveFromRoot, distDir, createLogger } from "../build";
const logger = createLogger("android");
const APK_PATTERN = /release\.apk$/i;
function copyArtifactsToDist() {
logger.logHeader("Copying APK to Dist", { repeatChar: "=" });
const baseDir = `${androidDirectory}/app/build/outputs/apk`;
const allFlavs = ["dev", "qa", "ua", "prod"];
const branchName = process.env.GitVersion_BranchName || "";
const buildFlavour = branchName.startsWith("release/") ? allFlavs : ["dev"];
const envs = {
dev: "INT",
qa: "QA",
ua: "UA",
prod: ""
};
buildFlavour
.map(env => {
const apkOutputDir = resolveFromRoot(`${baseDir}/${env}/release`);
return {
apkOutputDir,
env
};
})
.forEach(({ apkOutputDir, env }) => {
const src = `${apkOutputDir}/app-${env}-release.apk`;
//prettier-ignore
const binaryName = env === 'prod' ? 'ENGAL.apk' : `ENGAL-${envs[env]}.apk`;
const dest = `${distDir}/${binaryName}`;
fs.copy(src, dest, (err: Error) => {
if (err) {
logger.error(err);
}
});
});
}
function run() {
logger.logHeader("Starting Android Builds", { repeatChar: "#" });
const flavours = [
{
endpoint: "dv",
flavour: "Dev",
appcenterKey: "<hashKeys>"
},
{
endpoint: "qa",
flavour: "Qa",
appcenterKey: "<hashKeys>"
},
{
endpoint: "ua",
flavour: "Ua",
appcenterKey: "<hashKeys>"
},
{
endpoint: "prod",
flavour: "Prod",
appcenterKey: "<hashKeys>"
}
];
const versionCode = process.env.Build || 1;
const release = process.env.GitVersion_MajorMinorPatch || "1.0.0";
const fullAppVersion = `${release}-${versionCode}`;
const devFlav = flavours.find(f => f.flavour.toLocaleLowerCase() === "dev");
const branchName = process.env.GitVersion_BranchName || "";
const buildFlavour = branchName.startsWith("release/") ? flavours : [devFlav];
eachSeries(
buildFlavour,
(f, callback) => {
//prettier-ignore
logger.logHeader(
`starting gradle assemble${f.flavour}Release with flag - versionName=${fullAppVersion} -PversionCode=${versionCode}`,
{repeatChar: '-'}
);
const engaInfo = `ENGAGE_VERSION=${fullAppVersion}`;
const engaEndpoint = `ENGAGE_ENDPOINT=${f.endpoint}`;
const engaCenter = `APPCENTER_KEY=${f.appcenterKey}`;
const engaPlatform = "APPCENTER_PLATFORM=android";
//prettier-ignore
const prepare = `${engaEndpoint} ${engaCenter} ${engaInfo} ${engaPlatform} npm run setup`;
const cd = `cd ${androidDirectory}`;
//prettier-ignore
const releaseCmd = `./gradlew assemble${f.flavour}Release -PversionName=${fullAppVersion} -PversionCode=${versionCode} && cd ..`;
exec(`${prepare} && ${cd} && ${releaseCmd}`, err => {
if (err) {
return callback(err);
}
logger.logHeader(`${f.flavour} Android Build Successful!`, {
repeatChar: "#"
});
logger.close();
callback(null);
});
},
error => {
if (error) {
logger.logHeader("Android Builds Failed!", {
repeatChar: "#"
});
logger.error(error);
logger.close();
}
copyArtifactsToDist();
}
);
}
run();
via npm run build and locally I got this error:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'assembleDevRelease' not found in root project 'AppName'. Some candidates are: 'assembleRelease'.
Are these related errors? Anyone experienced with React Native builds?
As suggested, I looked into my android/app/build.gradle file for productFlavors and noticed that indeed they were missing between here:
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 123456 + defaultConfig.versionCode
}
}
}
So I added it like so:
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
productFlavors {
dev {
resValue "string", "app_name", getAppName("INT")
resValue "string", "link_launcher", getLauncher("dv")
applicationIdSuffix ".dv"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
qa {
resValue "string", "app_name", getAppName("QA")
resValue "string", "link_launcher", getLauncher("qa")
applicationIdSuffix ".qa"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
ua {
resValue "string", "app_name", getAppName("UA")
resValue "string", "link_launcher", getLauncher("ua")
applicationIdSuffix ".ua"
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "123456789"]
}
prod {
resValue "string", "app_name", getAppName()
resValue "string", "link_launcher", getLauncher()
manifestPlaceholders = [onesignal_app_id: "<hash_id>",
onesignal_google_project_number: "601125149914"]
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
The buildTypes is looking a bit different than the original legacy buildTypes so I am not sure if that's okay, but at any rate I then ran npm run build again locally and got this error:
* Where:
Build file '/Users/danale/Projects/NFIBEngage/android/app/build.gradle' line: 168
* What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method getAppName() for arguments [INT] on ProductFlavor_Decorated{name=dev, dimension=null, minSdkVersion=null, targetSdkVersion=null, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=null, versionName=null, applicationId=null, testApplicationId=null, testInstrumentationRunner=null, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null, signingConfig=null, resConfig=null, mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={}, mWearAppUnbundled=null} of type com.android.build.gradle.internal.dsl.ProductFlavor.
I was able to resolve the local error by adding the missing methods like so:
def appName = "Engage";
/**
* Get the version name from command line param
*
* #return int If the param -PversionName is present then return int value or -1
*/
def getAppName = { env ->
return (env ? appName + " ("+ env + ")" : appName);
}
/**
* Get the version name from command line param
*
* #return int If the param -PversionName is present then return int value or -1
*/
def getLauncher = { env ->
return (env ? "engage-" + env + ".nfib.org" : "engage.nfib.org");
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions "default"
defaultConfig {
applicationId "com.nfib.engage"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
productFlavors {
dev {
dimension 'default'
resValue "string", "app_name", getAppName("INT")
resValue "string", "link_launcher", getLauncher("dv")
applicationIdSuffix ".dv"
manifestPlaceholders = [onesignal_app_id: "b78285eb-f1ec-46f3-9ad0-c7efe691a401",
onesignal_google_project_number: "584236827312"]
}
qa {
dimension 'default'
resValue "string", "app_name", getAppName("QA")
resValue "string", "link_launcher", getLauncher("qa")
applicationIdSuffix ".qa"
manifestPlaceholders = [onesignal_app_id: "e4280f5e-62ec-41a4-bd86-f5b94e471a36",
onesignal_google_project_number: "162802054510"]
}
ua {
dimension 'default'
resValue "string", "app_name", getAppName("UA")
resValue "string", "link_launcher", getLauncher("ua")
applicationIdSuffix ".ua"
manifestPlaceholders = [onesignal_app_id: "2ffd8dc0-9c6b-4035-999d-fc694194725a",
onesignal_google_project_number: "594905904045"]
}
prod {
dimension 'default'
resValue "string", "app_name", getAppName()
resValue "string", "link_launcher", getLauncher()
manifestPlaceholders = [onesignal_app_id: "82dcb42f-1d35-4b79-bc28-2d1d02dbda36",
onesignal_google_project_number: "601125149914"]
}
}
Unfortunately, I continue to get the same error in Jenkins.
Some of the changes to get the build working, from comments:
From your package.json, your cli version is at ^2.0.1 and 2.0.1 is indeed the version of the cli that had the issue you linked to from github.com/facebook/react-native/issues/25479 Have you verified that the line similar to def command = "../node_modules/.bin/react-native config" (from github.com/facebook/react-native/issues/…) in your node_modules/#react-native-community/cli-platform-android/native_modules.gradle is correct? You should also ensure your installed version of the cli is >= 2.0.2.
Make sure your buildTypes and productFlavors definitions in android/app/build.gradle are set up to include all the different variants you are trying to build in your jenkins job. Looks like you have flavors for dev, qa, ua and prod. Check out the gradle docs developer.android.com/studio/build/build-variants#build-types for more info.
Looks like you're missing a getAppName function in your build.gradle. Something like ext.getAppName = {suffix = '' -> 'MyAppName' + suffix}. A quick scan of your build.gradle looks like you need another called getLauncher which returns an appropriate string for whatever you use link_launcher for.
I upgraded my node version on my CI tool and fixed this exact error.
I was previously on version 6 and bumped it to 10
I have also face this problem
very easy solution for this problem
Remove node_module
and
Reinstall node_module : npm install
react-native run-android

React-Native LocalizedStrings.js - undefined is not an object

I'm starting to code in React-Native and, when trying to use the ReactLocalization library im getting the following error codes:
undefined is not an object (evaluating 'localization.language')
<unknown>
LocalizedStrings.js:17
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:65
_require
require.js:49
<unknown>
localizedStrings.js:3
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:65
_require
require.js:49
<unknown>
myWebView.js:25
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:65
_require
require.js:49
<unknown>
app.js:30
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:65
_require
require.js:49
<unknown>
index.js:15
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:65
_require
require.js:49
<unknown>
index.android.js:11
loadModuleImplementation
require.js:122
guardedLoadModule
require.js:58
_require
require.js:49
global code
require-0.js:1
I've tried to research but as the framework is way new there is not a lot information around.
Thank you in advance!
EDIT: Here is the class code
'use strict';
/**
* Simple module to localize the React interface using the same syntax
* used in the ReactNativeLocalization module
* (https://github.com/stefalda/ReactNativeLocalization)
*
* Originally developed by Stefano Falda (stefano.falda#gmail.com)
*
* It uses a call to the Navigator/Browser object to get the current interface language,
* then display the correct language strings or the default language (the first
* one if a match is not found).
*
* How to use:
* Check the instructions at:
* https://github.com/stefalda/react-localization
*/
export default class LocalizedStrings {
_getBestMatchingLanguage(language, props) {
//If an object with the passed language key exists return it
if (props[language]) return language;
//if the string is composed try to find a match with only the first language identifiers (en-US --> en)
var idx = language.indexOf("-");
if (idx >= 0) {
language = language.substring(0, idx);
if (props[language]) return language;
}
//Return the default language (the first coded)
return Object.keys(props)[0];
}
constructor(props) {
this.interfaceLanguage = (typeof navigator !== 'undefined' && navigator.languages && typeof navigator.languages !== 'undefined' && navigator.languages[0] && typeof navigator.languages[0] !== 'undefined') ? navigator.languages[0] :
((typeof navigator !== 'undefined' && navigator.language && typeof navigator.language !== 'undefined') ? navigator.language :
((typeof navigator !== 'undefined' && navigator.userLanguage && typeof navigator.userLanguage !== 'undefined') ? navigator.userLanguage :
'en-US'));
//Store locally the passed strings
this.props = props;
this.defaultLanguage = Object.keys(props)[0];
//Set language to its default value (the interface)
this.setLanguage(this.interfaceLanguage);
}
//Can be used from ouside the class to force a particular language
//independently from the interface one
setLanguage(language) {
//Check if a translation exists for the current language or if the default
//should be used
var bestLanguage = this._getBestMatchingLanguage(language, this.props);
this.language = bestLanguage;
//Associate the language object to the this object
if (this.props[bestLanguage]) {
//console.log("There are strings for the language:"+language);
//Merge default
var localizedStrings = {...this.props[this.defaultLanguage], ...this.props[this.language] };
for (var key in localizedStrings) {
//console.log("Checking property:"+key);
if (localizedStrings.hasOwnProperty(key)) {
//console.log("Associating property:"+key);
this[key] = localizedStrings[key];
}
}
}
}
//The current language displayed (could differ from the interface language
// if it has been forced manually and a matching translation has been found)
getLanguage() {
return this.language;
}
//The current interface language (could differ from the language displayed)
getInterfaceLanguage() {
return this.interfaceLanguage;
}
//Return an array containing the available languages passed as props in the constructor
getAvailableLanguages() {
if (!this.availableLanguages) {
this.availableLanguages = [];
for (let language in this.props) {
this.availableLanguages.push(language);
}
}
return this.availableLanguages;
}
//Format the passed string replacing the numbered placeholders
//i.e. I'd like some {0} and {1}, or just {0}
//Use example:
// strings.formatString(strings.question, strings.bread, strings.butter)
formatString(str, ...values) {
var res = str;
for (let i = 0; i < values.length; i++) {
res = this._replaceAll("{" + i + "}", values[i], res);
}
return res;
}
//Return a string with the passed key in a different language
getString(key, language) {
try {
return this.props[language][key];
} catch (ex) {
console.log("No localization found for key " + key + " and language " + language);
}
return null;
}
//Replace all occorrencies of a string in another using RegExp
_replaceAll(find, replace, str) {
//Escape find
find = find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return str.replace(new RegExp(find, 'g'), replace);
}
}
Changed the above code with this one:
https://github.com/stefalda/react-localization/blob/master/src/LocalizedStrings.js
and the error went away.