Uhandled atob variable on screen rendering - react-native

The error I get is [Unhandled promise rejection: ReferenceError: Can't find variable: atob].
And my screen code:
import React, { Component } from "react";
import { View, StatusBar, Text } from "react-native";
import firebase from "firebase";
import "firebase/firestore";
import { RowItem } from "../components/RowItem";
import { Header, Left, Right, Icon } from "native-base";
const styles = {
container: {
flexDirection: "row",
flexWrap: "wrap",
padding: 20
}
};
class QuizIndex extends Component {
constructor(props) {
super(props);
this.state = {
docs: []
};
}
async componentDidMount() {
await this.quizes();
}
quizes = async () => {
let result = await firebase
.firestore()
.collection("quiz")
.where("parentId", "==", "")
.get()
.then(r => {
console.log("fine");
})
.catch(e => {
console.log("Not fine");
});
const docs = result.docs.map(doc => {
return { uid: doc.id, ...doc.data() };
});
return this.setState({ docs });
};
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="dark-content" />
{this.state.docs.map(doc => (
<RowItem
key={doc.uid}
parentId={doc.parentId}
name={doc.title}
color={doc.color}
icon={doc.icon}
onPress={() =>
this.props.navigation.navigate("QuizSub", {
title: doc.title,
color: doc.color,
parentId: doc.uid
})
}
/>
))}
</View>
);
}
}
export default QuizIndex;
I don't get it where this problem occur because the things were working fine. Do you have any suggestion about this ? I googled it but none of the solutions helped me.

It's an issue in firebase dependency
Try to use version 7.9.0, this version will work fine.
yarn add firebase#7.9.0

I think if you install the base-64 npm package it will solve, but don't quite know why this is happening.
yarn add base-64
#or
npm install base-64
At App.js add:
import {decode, encode} from 'base-64'
if (!global.btoa) { global.btoa = encode }
if (!global.atob) { global.atob = decode }

Related

Auto update Net Info status in react-native

I am using https://github.com/react-native-community/react-native-netinfo to check network connection in my react-native app. How can fetch network connection automatically when Network is lost and the Network is back again?
Below is the code I using.
import React, { Component } from 'react';
import NetInfo from '#react-native-community/netinfo'
import { View, Text,StyleSheet,Dimensions } from 'react-native';
export default class NetStatus extends Component {
constructor(props) {
super (props)
this.state = {
isConnected:''
};
}
componentDidMount() {
this.handleConnectivityChange()
}
componentWillUnmount() {
this.handleConnectivityChange()
}
handleConnectivityChange(){
NetInfo.fetch().then(isConnected => {
this.setState({ isConnected:isConnected.isInternetReachable });
console.log('isConnected : ', isConnected);
})
};
render() {
return (
<View>
{this.state.isConnected === true ?
null
:(
<View style={styles.container}>
<Text style={{color:'#FFF'}}>
You are not connected to internet....!
</Text>
</View>
)
}
</View>
);
}
}
How can I get the network status without fetching every time when Network is lost and the Network is back again?
You have to add a listener to NetInfo.
Following code can help you,
const [networkState, setNetworkState] = useState(true);
const onNetworkStateChange = (newState) => {
setNetworkState(newState.isConnected);
if (!newState.isConnected) {
// do anything you want
}
};
const initialCheck = () =>
NetInfo.fetch().then((connectionInfo) => {
setNetworkState(connectionInfo.isConnected);
});
useEffect(() => {
initialCheck();
NetInfo.addEventListener(onNetworkStateChange);
}, []);

TypeError : undefined not an object - AsyncStorage

Hi I cant seem to solve this issue - I am using AsyncStorage in a React Native component to load file path strings. I am getting the below error when the component mounts and failing to see what I am doing incorrectly here as it pretty much follows the documented examples.
any help would be appreciated.
"TypeError: undefined is not an object (evaluating '_asyncStorage.AsyncStorage.getKeys')
here is my code :
import React, { Component } from 'react';
import BasicCard from './cards'
import {AsyncStorage} from '#react-native-community/async-storage'
import {
StyleSheet,
ScrollView,
} from 'react-native';
class NewPost extends Component{
state={
content:[]
}
componentDidMount(){
this.getContent(this.getKeys())
}
getKeys = async () => {
try{
return await AsyncStorage.getKeys()
}catch (e) {
alert(e)
}
}
getContent = async (keys) => {
try{
await AsyncStorage.multiGet(keys, store)
this.setState({content:store})
} catch (e) {
alert ( e )
}
}
render(){
return(
<ScrollView style={styles.container}>
{this.state.content.map((result,i,item) => (
<BasicCard
imgName={item[i][0]}
imgPath={item[i[1]]} />
))}
</ScrollView>
)
}
}
export default NewPost;
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
},
});
There is no function called getkeys in asyncStorage
refer this link to know the available functions in async storage
getKeys = async () => {
try{
return await AsyncStorage.getKeys()
}catch (e) {
alert(e)
}
}
change to this
getKeys = async () => {
try{
return await AsyncStorage.getAllKeys()
}catch (e) {
alert(e)
}
}

Lodash debounce not working all of a sudden?

I'm using a component I wrote for one app, in a newer app. The code is like 99% identical between the first app, which is working, and the second app. Everything is fine except that debounce is not activating in the new app. What am I doing wrong?
// #flow
import type { Location } from "../redux/reducers/locationReducer";
import * as React from "react";
import { Text, TextInput, View, TouchableOpacity } from "react-native";
import { Input } from "react-native-elements";
import { GoogleMapsApiKey } from "../../.secrets";
import _, { debounce } from "lodash";
import { connect } from "react-redux";
import { setCurrentRegion } from "../redux/actions/locationActions";
export class AutoFillMapSearch extends React.Component<Props, State> {
textInput: ?TextInput;
state: State = {
address: "",
addressPredictions: [],
showPredictions: false
};
async handleAddressChange() {
console.log("handleAddressChange");
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleMapsApiKey}&input=${this.state.address}`;
try {
const result = await fetch(url);
const json = await result.json();
if (json.error_message) throw Error(json.error_message);
this.setState({
addressPredictions: json.predictions,
showPredictions: true
});
// debugger;
} catch (err) {
console.warn(err);
}
}
onChangeText = async (address: string) => {
await this.setState({ address });
console.log("onChangeText");
debounce(this.handleAddressChange.bind(this), 800); // console.log(debounce) confirms that the function is importing correctly.
};
render() {
const predictions = this.state.addressPredictions.map(prediction => (
<TouchableOpacity
style={styles.prediction}
key={prediction.id}
onPress={() => {
this.props.beforeOnPress();
this.onPredictionSelect(prediction);
}}
>
<Text style={text.prediction}>{prediction.description}</Text>
</TouchableOpacity>
));
return (
<View>
<TextInput
ref={ref => (this.textInput = ref)}
onChangeText={this.onChangeText}
value={this.state.address}
style={[styles.input, this.props.style]}
placeholder={"Search"}
autoCorrect={false}
clearButtonMode={"while-editing"}
onBlur={() => {
this.setState({ showPredictions: false });
}}
/>
{this.state.showPredictions && (
<View style={styles.predictionsContainer}>{predictions}</View>
)}
</View>
);
}
}
export default connect(
null,
{ setCurrentRegion }
)(AutoFillMapSearch);
I noticed that the difference in the code was that the older app called handleAddressChange as a second argument to setState. Flow was complaining about this in the new app so I thought async/awaiting setState would work the same way.
So changing it to this works fine (with no flow complaints for some reason. maybe because I've since installed flow-typed lodash. God I love flow-typed!):
onChangeText = async (address: string) => {
this.setState(
{ address },
_.debounce(this.handleAddressChange.bind(this), 800)
);
};

bundling failed: SyntaxError in D:\RN\AtmosphericMeshing-\src\router.js: D:/RN/AtmosphericMeshing-/src/router.js: Unexpected token (16:0)

everyone, I have been reporting wrong when I used the react-native compilation project, I don't know how to solve it, I can't find the error, please give me some Suggestions, thank you very much.
import React, { PureComponent } from 'react';
import { BackHandler, Platform, View, StatusBar, Text,Modal } from 'react-native';
import {
addNavigationHelpers
} from 'react-navigation';
import { connect } from 'react-redux';
import moment from 'moment';
import SplashScreen from 'react-native-splash-screen';
import { loadToken, getNetConfig, saveNetConfig, loadNetConfig } from './dvapack/storage';
import { createAction, NavigationActions, getCurrentScreen } from './utils';
import NetConfig from './config/NetConfig.json';
import api from './config/globalapi';
import AppNavigator from './containers/';
*I don't know if this is the correct way of writing the router, and it has led to this problem.*
#connect(({ router }) => ({ router }))***//一直报这里的错误=I've been making mistakes here.***
class Router extends PureComponent {
constructor(props) {
super(props);
this.state = {
configload: true
};
}
async componentWillMount() {
let netconfig =await loadNetConfig();
if (!netconfig && !netconfig != null) {
if (NetConfig.isAutoLoad) {
const newconfig = [];
NetConfig.Config.map((item, key) => {
const netitem = {};
// netitem.neturl = `http://${item.configIp}:${item.configPort}`+api.appurl;
netitem.neturl = `http://${item.configIp}:${item.configPort}`;
if (key === 0) {
netitem.isuse = true;
} else {
netitem.isuse = false;
}
newconfig.push(netitem);
});
saveNetConfig(newconfig);
} else {
this.setState({ configload: false });
SplashScreen.hide();
}
}
BackHandler.addEventListener('hardwareBackPress', this.backHandle);
}
async componentDidMount() {
const user = await loadToken();
this.props.dispatch(createAction('app/loadglobalvariable')({ user }));
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress', this.backHandle);
JPushModule.removeReceiveCustomMsgListener(receiveCustomMsgEvent);
JPushModule.removeReceiveNotificationListener(receiveNotificationEvent);
JPushModule.removeReceiveOpenNotificationListener(openNotificationEvent);
JPushModule.removeGetRegistrationIdListener(getRegistrationIdEvent);
JPushModule.clearAllNotifications();
} else {
DeviceEventEmitter.removeAllListeners();
NativeAppEventEmitter.removeAllListeners();
}
}
backHandle = () => {
const currentScreen = getCurrentScreen(this.props.router);
//登录
if (currentScreen === 'Login') {
return true;
}
if (currentScreen !== 'Home') {
this.props.dispatch(NavigationActions.back());
return true;
}
return false;
}
render() {
if (!this.state.configload) {
return (
<View style={{ flex: 1 }}>
<StatusBar
barStyle="light-content"
/>
{/* <ScanNetConfig ScanSuccess={() => {
this.setState({ configload: true });
}}
/> */}
<Text>ScanNetConfig</Text>
</View>
);
}
const { dispatch, router } = this.props;
const navigation = addNavigationHelpers({ dispatch, state: router });
return (
<View style={{ flex: 1 }}>
<AppNavigator navigation={navigation} />
</View>
);
}
}
export function routerReducer(state, action = {}) {
return AppNavigator.router.getStateForAction(action, state);
}
export default Router;
Need More Detail?
this is the error.
bundling failed: SyntaxError in D:\RN\AtmosphericMeshing-\src\router.js: D:/RN/AtmosphericMeshing-/src/router.js: Unexpected token (16:0)
I find the Solution
.babelrc needs to be changed:
{
"presets": ["react-native"],
"plugins": [
"syntax-decorators",
"transform-decorators-legacy",
["import", { "libraryName": "antd-mobile" }]
]
}

React-Native Navigator is deprecated and has been removed from this package

I get the following error.
Navigator is deprecated and has been removed from this package. It can now be installed and imported from react-native-deprecated-custom-components instead of react-native. Learn about alternative navigation solutions at http://facebook.github.io/react-native/docs/navigation.html
Then I would update react-native-deprecated-custom-components package but issue not solved
Package.Json
"dependencies": {
"react": "16.0.0-alpha.6",
"react-native": "0.44.2",
"react-native-deprecated-custom-components": "^0.1.0",
"sendbird": "^3.0.30"
},
main.js
var React = require('react-native')
var {
Navigator,
StyleSheet
} = React;
var Login = require('./components/login');
import NavigationExperimental from 'react-native-deprecated-custom-components';
var ROUTES = {
login: Login
};
module.exports = React.createClass({
renderScene: function(route, navigator) {
var Component = ROUTES[route.name];
return <Component route={route} navigator={navigator} />;
},
render: function() {
return (
<NavigationExperimental.Navigator
style={ styles.container }
initialRoute={ {name: 'login'} }
renderScene={this.renderScene}
configureScene={ () => { return Navigator.SceneConfigs.FloatFromRight; } }
/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1
}
});
Any one let me know to solve this issue
Ive use below code to fix my issue
main.js
var React = require('react-native')
var {
Navigator,
StyleSheet
} = React;
var Login = require('./components/login');
import NavigationExperimental from 'react-native-deprecated-custom-components';
var ROUTES = {
login: Login
};
module.exports = React.createClass({
renderScene: function(route, navigator) {
var Component = ROUTES[route.name];
return <Component route={route} navigator={navigator} />;
},
render: function() {
return (
<NavigationExperimental.Navigator
style={ styles.container }
initialRoute={ {name: 'login'} }
renderScene={this.renderScene}
configureScene={ () => { return NavigationExperimental.Navigator.SceneConfigs.FloatFromRight; } }
/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1
}
});
Any one let me know to solve this issue
I've change the lines
configureScene={ () => { return NavigationExperimental.Navigator.SceneConfigs.FloatFromRight; } }
To
configureScene={ () => { return NavigationExperimental.Navigator.SceneConfigs.FloatFromRight; } }
Fix my issue
You should use Stack Navigator now
import { StackNavigator } from 'react-navigation';
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen },
});
<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>
reference : https://reactnavigation.org/docs/intro/
If anyone is seeing this while not even trying to use Navigator, it’s possibly because you’ve got an import line like
import * as RN from 'react-native'
(Webstorm in particular has a habit of auto-inserting these)
This calls the getters for all of RN’s exports, triggering the error for Navigator. Instead use:
import {Things, You, Need} from 'react-native'