react-native asking Android runtime permission - javascript

I'm trying to ask for Android permissions within my React Native app. I followed the official documentation here and I get this runtime error (from the react-native log-androidcommand) :
W ReactNativeJS: undefined is not an object (evaluating 'PermissionsAndroid.PERMISSIONS.CAMERA')
This is the code I actually have :
My import (generated by WebStorm) :
import * as PermissionsAndroid from "react-native";
The code that actually ask for the permission :
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
'title': 'A title',
'message': 'A message'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
return true;
} else {
return false;
}
} catch (err) {
console.warn(err)
}
}
I can't understand why this doesn't work since it comes from the official documentation.

In short words: you should import a single member of react-native module. This will look like this:
import { PermissionsAndroid } from 'react-native';
What causes the problem is your import syntax. In your example you are importing the whole react-native module as PermissionAndroid variable in your module. But as you see from my code line you need only a single member from the whole package.
As for me, it was really a good idea to try different ES6 import syntax in real world and to get used to them.

Related

Why is dynamic importing of dayjs not working in typescript?

I am working on a web screen inside a .NET app and I am trying to send date time preference from the system to the web screen using CefSharp settings and setting
AcceptLanguageList = CultureInfo.CurrentUICulture.Name
In my typescript code I want to use dayjs and import dynamically 'dayjs/locale/${language}' where language comes from AcceptLanguageList above.
import React, { useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import localeData from 'dayjs/plugin/localeData';
dayjs.extend(localeData);
var lang = navigator.languages != null ? navigator.languages[0] : navigator.language;
lang = lang.toLowerCase();
import(`dayjs/locale/${lang}`).then(
() => {
dayjs.locale(lang);
setAdapterLocale(lang);
});
The thing is, when I run this code in browser and try to import 'dayjs/locale/fr-ca', for example, it works fine, but when 'fr-ca' comes from CefSharp, then the import fails with
Uncaught (in promise) TypeError: Failed to resolve module specifier
'dayjs/locale/fr-ca'
Any help is much appreciated.
If you want to use a dynamic path for the dynamic import then you'll first have to list all of the possible paths that you will potentially want to have, otherwise your bundler wont know which files to include.
You can add import('dayjs/locale/fr-ca') anywhere in your code and the bundler will include it when it builds your app for the browser.
And you'll still going to get that error if you don't have a locale for user's language, so you should catch that case:
import(`dayjs/locale/${lang}`).then(
() => {
dayjs.locale(lang);
setAdapterLocale(lang);
},
() => { // in case the import fails
// maybe default to english
dayjs.locale('en');
setAdapterLocale('en');
});
I figured it out. The problem was that when building the package for the .net app, the package was created using rollup (which is not the case when running in browser).
Rollup needs some special config to support dynamic import:
https://www.npmjs.com/package/#rollup/plugin-dynamic-import-vars

Determine javascript framework based on importation

I am writing a python script that determine the type of javascript framework used in file, I am having issue in detecting when whether the code is node.js file or react.js file. I tried detecting via importation , so far when I have import React from 'react'; I know directly it is react file , but the problem is when we don't have react importation but the file is part of react project ( for eg file contain reducer, hooks) and I have have othe importation, my idea is to to check whether that importation is react , the problem is even if I check npm registry it don't give me info about whether the package is for node.js apps or for react or other. For example this code ,how can I determine whetehr it is node or react or other ?
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
const LowercaseString = new GraphQLScalarType({
name: 'LowercaseString',
description: 'Returns all strings in lower case',
parseValue(value) {
return value.toLowerCase();
},
serialize(value) {
return value.toLowerCase();
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return ast.value.toLowerCase();
}
return null;
},
});
export default LowercaseString;

react-native expo error: Unhandled promise rejection: TypeError: null is not an object (evaluating 'RNAlarmNotification.scheduleAlarm')

I'm trying to use a notification package (react-native-alarm-notification) in my React Native project, but am running into some issues. After installing, trying to run scheduleAlarm() results in the following error:
[Unhandled promise rejection: TypeError: null is not an object (evaluating  'RNAlarmNotification.scheduleAlarm')].
I'm not entirely certain what the issue is, as the 'required' parameters of scheduleAlarm are filled and I am uncertain as to what null object is throwing an error. Attempting to fill every possible parameter in scheduleAlarm still returns with null, as does giving only an alarm date and assuming default values are assigned. Tracing the error location however shows the error coming from the regenerator-runtime and react-native modules that came from the default React project build, not from the notification package.
Does anyone have a solution to the problem? 
Function.js:
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import ReactNativeAN from 'react-native-alarm-notification';
export default function ShowTasks() {
async function alarmTest(){
console.log("Alarm test start");
const fireDate = ReactNativeAN.parseDate(new Date(Date.now() + 10000));
const alarmNotifData = {
title: "My Notification Title",
message: "My Notification Message",
channel: "my_channel_id",
small_icon: "../icon.png",
scheduleType:"once",
data: { foo: "bar" },
fire_date:fireDate,
};
const alarm = await ReactNativeAN.scheduleAlarm({...alarmNotifData});
console.log("Alarm test finish");
}
return (
<View>
<Button onPress={() => {alarmTest();}}
title= 'Click here to test alarm.'>
</Button>
<StatusBar style="auto" />
</View>
);
}
Rebuilding the App solved my issue:
npx react-native run-android
For android, the package will be linked automatically on the build.
but if it doesn't then You need to link it manually.
Make following changes:
android/app/src/main/java//MainApplication.java
add import com.emekalites.react.alarm.notification.ANPackage; on the imports section
add packages.add(new ANPackage()); in List<ReactPackage> getPackages();
android/app/build.gradle
add implementation project(':react-native-alarm-notification') in the dependencies block
android/settings.gradle
add:
include ':react-native-alarm-notification'
project(':react-native-alarm-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-alarm-notification/android')
Checkout the documentation here

React Native Sound Not Working (Remote URL)

Code :
import React, { Component } from 'react'
import { Button } from 'react-native'
import Sound from 'react-native-sound';
class RemoteSound extends Component {
playTrack = () => {
const track = new Sound('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3', null, (e) => {
if (e) {
alert('error loading track:', e)
} else {
track.play()
}
})
}
render() {
return <Button title="play me" onPress={()=>{
this.playTrack();
}} />
}
}
export default RemoteSound
Problem : when I add this line "import Sound from 'react-native-sound'" ,
I got this error : Cannot read property 'IsAndroid' of undefined
Evaluating react-native-sound.js
and remote url not playing.
Question 1 : this library not used any more react-native-sound
Question 2 : do you have current example in react native . In many websites , I tried many example but all of them is not working.
As stated in the repo home page:
If you encounter this error
undefined is not an object (evaluating 'RNSound.IsAndroid')
know that this is the most common build issue. See #592 and the
several issues linked from it for possible resolution. A pull request
with improved documentation on this would be welcome!
Depending on your environment (operating system, docker, etc) the solution may vary. Please, visit that issue #592 for more details, or add relevant info to the question.

react-localize-redux cannot read property 'map' of undefined

I'm trying to load translations from a JSON file with react-localize-redux and I keep getting this error. This is all fairly new to me so I apologise if it is something obvious. As fair as I can tell from reading documentation this "should" work?
The error message I am receiving:
translate.js
import { combineReducers, createStore } from 'redux'
import { localizeReducer, initialize, addTranslationForLanguage, getTranslate } from 'react-localize-redux'
import translationsEn from '../../../nls/en.json'
const localeStore = createStore(combineReducers({
locale: localizeReducer
}))
const languages = ['en']
localeStore.dispatch(initialize(languages))
localeStore.dispatch(addTranslationForLanguage(translationsEn, 'en'))
export default getTranslate(localeStore.getState().locale)
and in my component:
import translate from '../state/translate/translate'
...
<span className='node-output-schema__title'>{translate('outputSchema.title')}</span>
Any ideas to what might be going wrong?
it seems like you mixed some different frameworks inside here.
The localisation package is called - react-localize-redux.
But inside your error logs I can see that you are using some angular.
Also I just checked the documentation from the react-localize-redux package and it seems like you are working with an outdated version.
For me it should be enough to just provide a Provider to your app and afterwards use the higher order component (import { withLocalize } from "react-localize-redux";
)
Also I would recommend to use this package, which is a lot easier to handle (and indeed I used it for a project myselft)
react-18next (https://github.com/i18next/react-i18next)
this error rases because your property is undefined, so check your error and get the exact line(you can find the error on the console tab of your browser) and check which property used there and check where you filled that property if you didn't fill your property then set it

Categories