Accelerometer Problems in React-Native/Expo - react-native

I'm building an app on codeHS that utilizes an accelerometer.
I tried dragging and dropping the accelerometer component the website provides into the code I was writing just to see how the component would work.
When I tried to run the code the debugger gave me an error, stating that it couldn't read the addListener event, stating that it was undefined. What is causing the error? I appreciate any insight or tips.
Here is a copy of the code:
import React, { Component } from 'react';
import { AppRegistry, Text, View, Listener, StyleSheet, TouchableOpacity } from 'react-native';
import { Constants, Accelerometer } from 'expo';
export default class App extends Component {
componentWillUnmount() {
this._unsubscribeFromAccelerometer();
}
componentDidMount() {
this._subscribeToAccelerometer();
}
state = {
accelerometerData: { x: 0, y: 0, z: 0 }
};
_subscribeToAccelerometer = () => {
this._acceleroMeterSubscription = Accelerometer.addListener(accelerometerData =>
this.setState({ accelerometerData })
);
};
_unsubscribeFromAccelerometer = () => {
this._acceleroMeterSubscription && this._acceleroMeterSubscription.remove();
this._acceleroMeterSubscription = null;
};
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
<Text>
Accelerometer:
x = {this.state.accelerometerData.x.toFixed(2)}{', '}
y = {this.state.accelerometerData.y.toFixed(2)}{', '}
z = {this.state.accelerometerData.z.toFixed(2)}
</Text>
</Text>
</View>
);
}
}

Related

expo AppLoading startAsync Deprecated. what is the alternative?

I am learning react native from Udemy. In one of the lessons I saw AppLoading has been used for loading fonts.
So i want to learn about it in documentation from here. I am able to use that without any issues even though, I saw here that startAsync has been deprecated.
What is the alternative to this startAsync if it stopped working?
below is the code from documentation,
import React from 'react';
import { Image, Text, View } from 'react-native';
import { Asset } from 'expo-asset';
import AppLoading from 'expo-app-loading';
export default class App extends React.Component {
state = {
isReady: false,
};
render() {
if (!this.state.isReady) {
return (
<AppLoading
startAsync={this._cacheResourcesAsync}
onFinish={() => this.setState({ isReady: true })}
onError={console.warn}
/>
); }
return (
<View style={{ flex: 1 }}>
<Image source={require('./assets/snack-icon.png')} />
</View>
);
}
async _cacheResourcesAsync() {
const images = [require('./assets/snack-icon.png')];
const cacheImages = images.map(image => {
return Asset.fromModule(image).downloadAsync();
});
return Promise.all(cacheImages);
}
}
Call _cacheResourcesAsync function in componentDidMount and when all promised are resolved set state isReady to true like:
import React from 'react';
import { Image, Text, View } from 'react-native';
import { Asset } from 'expo-asset';
import AppLoading from 'expo-app-loading';
export default class App extends React.Component {
state = {
isReady: false,
};
componentDidMount(){
_cacheResourcesAsync();
}
render() {
if (!this.state.isReady) {
return (
<AppLoading />
); }
return (
<View style={{ flex: 1 }}>
<Image source={require('./assets/snack-icon.png')} />
</View>
);
}
_cacheResourcesAsync() {
const images = [require('./assets/snack-icon.png')];
const cacheImages = images.map(image => {
return Asset.fromModule(image).downloadAsync();
});
Promise.all(cacheImages).then(()=>{
this.setState({ isReady : true });
});
}
}
You should use a hook to load your images.
First, create a hook to load resources in a separate file:
import * as SplashScreen from 'expo-splash-screen';
import { useEffect, useState } from 'react';
export default function useCachedResources() {
const [isLoadingComplete, setLoadingComplete] = useState(false);
// Load any resources or data that we need prior to rendering the app
useEffect(() => {
async function loadResourcesAndDataAsync() {
try {
SplashScreen.preventAutoHideAsync();
// Load images
const images = [require('./assets/snack-icon.png')];
await images.map(async image =>
await Asset.fromModule(image).downloadAsync());
} catch (e) {
// We might want to provide this error information to an error reporting service
console.warn(e);
} finally {
setLoadingComplete(true);
SplashScreen.hideAsync();
}
}
loadResourcesAndDataAsync();
}, []);
return isLoadingComplete;
}
Then call it in your App component - I changed it to a function component, because hooks don't work in classes and it is now the recommended way of coding react:
import { Image, View } from 'react-native';
import useCachedResources from "./hooks/useCachedResources";
export default function App() {
const isLoadingComplete = useCachedResources();
if (!isLoadingComplete) {
return null;
}
return (
<View style={{ flex: 1 }}>
<Image source={require('./assets/snack-icon.png')} />
</View>
);
}

undefined is not an object(evaluating '_this.refs.toast.show')

My aim is to listen the event for Android homeback button, and then give a toast when continuous click. Here the third component "react-native-easy-toast" is used, fully code snippets shown as below:
import React, { Component } from 'react';
import {View, WebView, Platform, BackHandler, StyleSheet} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
export default class HomeScreen extends Component {
constructor (props) {
super(props);
}
onNavigationStateChange = (event) => {
this.setState({
navCanGoBack : event.canGoBack,
});
};
componentDidMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.onHomeBackPress);
}
}
onHomeBackPress = () => {
if (this.state.navCanGoBack) {
this.refs['webview'].goBack();
return true;
} else {
//exit app if exceed 2 seconds
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
return false;
}
this.lastBackPressed = Date.now();
this.refs.toast.show('weill exit app press again');
return true;
}
};
render() {
return (
<View style={{flex:1}}>
<WebView
source={{ uri: 'http://www.test.com/' }}
style={{ width: '100%', height: '100%' }}
ref="webview"
onNavigationStateChange={this.onNavigationStateChange}
/>
<Toast ref="toast" />
</View>
);
}
}
Finally, run the app and error given:
undefined is not an object(evaluating '_this.refs.toast.show')
I am newer to React Native.
Please try
//inside constructor
this.toastRef = React.createRef();
...
<Toast ref={this.toastRef} />
and replace
this.refs.toast.show('weill exit app press again');
to
this.toastRef.current.show('weill exit app press again');

"Cannot add a child that doesn't have YogaNode to a parent without a measure function "

While building a react-native application for Android I am getting the error
Cannot add a child that doesn't have Yoga Node to a parent without a
measure function
I tried with both remote debugger on and off but the problem persists.
Pasting my Component function as below.
import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';
import { connect } from 'react-redux';
import { CardSection } from './common';
import * as actions from '../actions';
class ListItem extends Component {
render() {
const { title, id } = this.props.library;
const { titleStyle } = styles;
return (
<TouchableWithoutFeedback
onPress ={() => this.props.selectLibrary(id)}
>
<View> /* Using View as more then one card section is used */
<CardSection>
<Text style={titleStyle} >
{title}
</Text>
</CardSection>
</View>
</TouchableWithoutFeedback>
)
}
}
const styles = {
titleStyle: {
fontSize:18,
paddingLeft:10
}
};
export default connect(null, actions)(ListItem);
The problem is resolved once I moved my comments in front of the View tag to other location ( for example, before return statement)

onPressIn getting called twice if view moves

I created a sort of demo on expo: https://snack.expo.io/#noitsnack/onpressin-twice
I tested this by scanning QR code in expo. This may be a expo bug.
I have wraped the expo symbol (an <Image>) in a <TouchableWithoutFeedback>. Here we see that when we press the expo symbol it causes the score to increase by one, and then the symbol moves to a new location. Sometimes it causes the onPressIn to trigger twice. I don't understand this, why does this happen?
Here is the code to the expo:
import React, { Component } from 'react';
import { Text, View, TouchableWithoutFeedback, Image, Dimensions } from 'react-native';
import IMAGE_EXPO from './assets/expo.symbol.white.png'
const IMAGE_SIZE = 100;
export default class App extends Component {
state = {
score: 0,
...getRandXY()
}
render() {
const { score, x, y } = this.state;
return (
<View style={{flex:1, backgroundColor:'steelblue' }}>
<Text style={{fontSize:72, textAlign:'center'}}>{score}</Text>
<TouchableWithoutFeedback onPressIn={this.addScore}>
<Image source={IMAGE_EXPO} style={{ width:IMAGE_SIZE, height:IMAGE_SIZE, left:x, top:y, position:'absolute' }} />
</TouchableWithoutFeedback>
</View>
)
}
addScore = e => {
this.setState(({ score }) => ({ score:score+1, ...getRandXY() }));
}
}
function getRandXY() {
return {
x: getRandInt(0, Dimensions.get('window').width - IMAGE_SIZE),
y: getRandInt(0, Dimensions.get('window').height - IMAGE_SIZE)
}
}
function getRandInt(min, max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}

Camera does not display, state transition issue, react-native

I've been trying to save an asyncstorage item, on touchableopacity onPress, then navigate to a react-native-camera screen.
Problem is: Camera screen get blank. I got the following error: Warning: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are anti-pattern, but can be moved to 'componentWillMount'.
Warning points to lines 27, 36 and 41 (at AddParameters class)
Here is the code:
AddParameters.js
import React, { Component } from 'react';
import {
Text,
AsyncStorage,
View,
TouchableOpacity,
} from 'react-native';
class AddParameters extends Component {
constructor() {
super()
this.state = {
localIds: [
"data1",
"data2",
"data3",
"data4",
"data5",
"data6"
],
}
}
renderScreen = () => {
return (
<TouchableOpacity onPress={this._AddParameter(this.state.localIds[0])}>
<Text>Click Me</Text>
</TouchableOpacity>
);
}
_AddParameter = (ParameterId) => {
const { navigate } = this.props.navigation;
AsyncStorage.setItem("myparam", ParameterId);
navigate("CameraScreen");
}
render() {
return (
this.renderScreen()
);
}
}
export default AddParameters;
CameraScreen.js
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
View,
Image,
AsyncStorage,
} from 'react-native';
import Camera from 'react-native-camera';
class CameraScreen extends Component {
constructor(props) {
super(props);
this.state = {
mystate: '',
};
}
renderCamera = () => {
return (
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={stylesCamera.container}
aspect={Camera.constants.Aspect.fill}>
</Camera>
);
}
render() {
return (
this.renderCamera()
);
}
}
const stylesCamera = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "transparent",
},
});
export default CameraScreen;
Any explanation would be helpfull. Thanks in advance.
On your AddParameters file try changing this:
<TouchableOpacity onPress={this._AddParameter(this.state.localIds[0])}>
To:
<TouchableOpacity onPress={() => this._AddParameter(this.state.localIds[0])}>