React Native Google API not responding - react-native

I have connected my app to google places API and I was working until a certain point (I'm not sure what changed) but the API is no longer receiving my request when I go check on the google developers console I neither shows 4XX or 2XX(previously showing)
this is my code
import React,{useState,useEffect} from "react";
import { View ,Text, TextInput ,SafeAreaView, ListView } from "react-native";
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import { useNavigation } from "#react-navigation/core";
import Styles from "./style";
import Place from "./PlaceRow";
const HomePlace={
description:"Home",
geometry:{location:{lat:48.8152937,lng:2.4597668}}
};
const WorkPlace={
description:"Work",
geometry:{location:{lat:48.8152837,lng:2.4597659}}
};
const DestinationSearch=(props)=>{
const navigation= useNavigation();
const [fromText , setFromText] = useState("");
const [destinationText , setDestinationText] = useState("");
useEffect(() => {
if(fromText && destinationText) {
navigation.navigate("SearchResults",{
fromText,
destinationText
})
}
}, [fromText,destinationText]);
return (
<SafeAreaView>
<View style={Styles.container}>
<GooglePlacesAutocomplete
placeholder="From"
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
setFromText(data, details);
}}
currentLocation={true}
currentLocationLabel='Current location'
styles={{
textInput:Styles.TextInput,
container:{
position:"absolute",
top:0,
left:10,
right:10,
},
listView:{
position:"absolute",
top:100,
}
}}
query={{
key: 'API CREDENTIALS',
language: 'en',
}}
predefinedPlaces={[HomePlace,WorkPlace]}
renderRow={(data)=><Place data={data}/>}
/>
<GooglePlacesAutocomplete
placeholder="Where to?"
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
setDestinationText(data, details);
}}
styles={{
textInput:Styles.TextInput,
container:{
position:"absolute",
top:55,
left:10,
right:10,
}
}}
query={{
key: 'API CREDENTIALS',
language: 'en',
}}
predefinedPlaces={[HomePlace,WorkPlace]}
renderRow={(data)=><Place data={data}/>}
/>
<View style={Styles.circle}/>
<View style={Styles.line}/>
<View style={Styles.square}/>
</View>
</SafeAreaView>
);
};
export default DestinationSearch;
I have tried
using the testing code provided by
react-native-google-places-autocomplete
creating a new API credential
waited for several days in case the server is down
reinstalling the NPM package
reenabled Google Places API

I solved the problem, turns out my android studio emulator disconnected to it's wifi
(dumb reason to get stuck on)

Related

Errors with reactNative/voice in expo

thats my code
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, Button, View } from 'react-native';
import { useEffect, useState } from 'react';
import Voice from '#react-native-voice/voice';
export default function App() {
let [started, setStarted] = useState(false);
let [results, setResults] = useState([]);
useEffect(() => {
Voice.onSpeechError = onSpeechError;
Voice.onSpeechResults = onSpeechResults;
return () => {
Voice.destroy().then(Voice.removeAllListeners);
}
}, []);
const startSpeechToText = async () => {
await Voice.start();
setStarted(true);
};
const stopSpeechToText = async () => {
await Voice.stop();
setStarted(false);
};
const onSpeechResults = (result) => {
setResults(result.value);
};
const onSpeechError = (error) => {
console.log(error);
};
return (
<View style={styles.container}>
{!started ? <Button title='Start Speech to Text' onPress={startSpeechToText} /> : undefined}
{started ? <Button title='Stop Speech to Text' onPress={stopSpeechToText} /> : undefined}
{results.map((result, index) => <Text key={index}>{result}</Text>)}
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
when I run it I keep getting this error
[Unhandled promise rejection: TypeError: null is not an object (evaluating 'Voice.startSpeech')]
I tried asking chatGPT but he can't answer it
Packages and import is correct, so I don't know what the error is nor how I can fix it
Check if it works on another version of android, I launched some emulators and it seems that below Android 12 there are problems with Permissions.
On Android 12 and above, my code with react-native-voice works well with expo run:android but I can't find out why once built with expo build:android I still have problems with mic permissions

Conditional rendering not working React Native IOS App

I am a developing an Iphone App using React Native. I want to display table using DataTable. For a User, they have specific devices assigned. I used conditional rendering and getting the table with assigned devices for a user correctly, but when the user has no specific devices I want a message to be displayed as 'No Devices to display'. Below is the code,
ManageDevice.js:
import React, {useEffect} from 'react';
import {View,Text,StyleSheet,ScrollView} from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import HeaderButton from '../../components/UI/HeaderButton';
import {useDispatch, useSelector} from "react-redux";
import {DataTable, TextInput} from 'react-native-paper';
import AsyncStorage from '#react-native-community/async-storage';
import * as authActions from "../../store/actions/auth";
const ManageDevice = props =>{
const dispatch = useDispatch();
const devices = useSelector(state => state?.auth?.availableDevice);
useEffect(() => {
const onScreenLoad = async () => {
const useridfordevices = await
AsyncStorage.getItem("userDatauserid");
const obj = JSON.parse(useridfordevices);
const {userid} = obj;
var userid1 = userid[0];
await dispatch(authActions.getDeviceInfo(userid1))
};
onScreenLoad();
}, [dispatch]);
if (devices)
{
return (
<ScrollView showsVerticalScrollIndicator={true}>
<View>
<DataTable>
<DataTable.Header>
<DataTable.Title>
<Text>Target Id</Text>
</DataTable.Title>
<DataTable.Title>
<Text>Target Name</Text>
</DataTable.Title>
</DataTable.Header>
{devices?.map((item, key) => (
<DataTable.Row>
<DataTable.Cell>{item.TargetId}</DataTable.Cell>
<DataTable.Cell><TextInput
editable={true}
value={item.TargetName}
theme={{ colors: { placeholder: "#f5f5f5",
background: "transparent",
text: 'green', primary: '#D43790' } }}>
</TextInput>
</DataTable.Cell>
</DataTable.Row>
)
)}
</DataTable>
<View style={styles.textview}>
<Text style={styles.textstyle}>Click on the Target Name to edit</Text>
</View>
</View>
</ScrollView>
)
}
else if(!devices){
return(
<View><Text>No Devices to display</Text></View>
)
}
}
ManageDevice.navigationOptions = navData =>{
return{
headerTitle: 'Manage Devices',
headerTitleStyle:{
color:'white',
},
headerTitleAlign:"left",
headerStyle: {
backgroundColor: '#0437F2',
},
headerLeft: () =>
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
iconName={'chevron-back-outline'}
onPress={() => {
navData.navigation.navigate('Home');
}}
/>
</HeaderButtons>
}
};
const styles = StyleSheet.create({
textview:{
top:'5%'
},
textstyle:{
fontWeight:'bold',
color:'orange'
}
})
export default ManageDevice;
Can anyone tell where I am going wrong? When 'devices' is empty, I want the 'No Devices to display' message. Thanks in Advance
Do it like this:
if(devices && devices?.length > 0){
return(
//Do Something
)
}
else{
return(
<View>
<Text>No Devices to display</Text>
</View>
)
}
Hope this works for you.

Amplify Tutorial (Expo) and got error message on signin

I'm doing this tutorial: https://docs.amplify.aws/start/getting-started/auth/q/integration/react-native#create-login-ui
I followed it completely and did everything they told me to do. The Todo works, but when I added Auth, and wrapped it. The project will start. Users can create accounts. But when you try to sign in on iOS it won't work. Strangely, when I tested it on web, users could sign in. Leading me to think it is a problem with iOS. I tested it on my iPhone with expo installed and it failed there too.
Here is a link to my issue: https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508
This is my app.js
import config from './aws-exports'
Amplify.configure(config)
import { withAuthenticator } from 'aws-amplify-react-native'
import React, { useEffect, useState } from 'react'
import {
View, Text, StyleSheet, TextInput, Button
} from 'react-native'
import { API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'
import { listTodos } from './graphql/queries'
const initialState = { name: '', description: '' }
const App = () => {
const [formState, setFormState] = useState(initialState)
const [todos, setTodos] = useState([])
useEffect(() => {
fetchTodos()
}, [])
function setInput(key, value) {
setFormState({ ...formState, [key]: value })
}
async function fetchTodos() {
try {
const todoData = await API.graphql(graphqlOperation(listTodos))
const todos = todoData.data.listTodos.items
setTodos(todos)
} catch (err) { console.log('error fetching todos') }
}
async function addTodo() {
try {
const todo = { ...formState }
setTodos([...todos, todo])
setFormState(initialState)
await API.graphql(graphqlOperation(createTodo, {input: todo}))
} catch (err) {
console.log('error creating todo:', err)
}
}
return (
<View style={styles.container}>
<TextInput
onChangeText={val => setInput('name', val)}
style={styles.input}
value={formState.name}
placeholder="Name"
/>
<TextInput
onChangeText={val => setInput('description', val)}
style={styles.input}
value={formState.description}
placeholder="Description"
/>
<Button title="Create Todo" onPress={addTodo} />
{
todos.map((todo, index) => (
<View key={todo.id ? todo.id : index} style={styles.todo}>
<Text style={styles.todoName}>{todo.name}</Text>
<Text>{todo.description}</Text>
</View>
))
}
</View>
)
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
todo: { marginBottom: 15 },
input: { height: 50, backgroundColor: '#ddd', marginBottom: 10, padding: 8 },
todoName: { fontSize: 18 }
})
export default withAuthenticator(App)```
I feel like the problem might be with the ./aws-exports potentially. There was a bug where you had to move it out of src, etc. Anyone have any ideas?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/1Wt6J.png
I found out that the login error was due to a bug with expo deprecating a file. See this issue for more. https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508

React Native - How to extract data from FaceDetector of Expo SDK?

I’m new to React Native and still learning React and JavaScript. I’m practicing on Expo snack with Expo's FaceDetector (SDK 37) and managed to generate data about faces. However, I couldn't (or don't know how to) extract these data. My goal for now is to render the rollAngle data in a Text component.
Here is the code I used in Expo Snack and tested with my Android cellphone:
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { Camera } from 'expo-camera';
import * as FaceDetector from 'expo-face-detector'
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [faces, setFaces] = useState([])
const faceDetected = ({faces}) => {
setFaces({faces})
console.log({faces})
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission !== true) {
return <Text>No access to camera</Text>
}
return (
//<View style={{ flex: 1 }}>
<Camera
style={{ flex: 1 }}
type='front'
onFacesDetected = {faceDetected}
FaceDetectorSettings = {{
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.all,
runClassifications: FaceDetector.Constants.Classifications.none,
minDetectionInterval: 5000,
tracking: false
}}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<Text style= {{top:200}}> is {faces[0].rollAngle} </Text>
</View>
</Camera>
//</View>
);
}
In the snack console, I see results like this:
Results in the Snack console
I tried to replace the faceDetected function with the following code:
const faceDetected = (faces) => {
setFaces(faces)
console.log(faces)
}
Then, the console shows slightly different results: Results in Snack console
I tried both ways to render rollAngle, but an error message showed up and said face[0].rollAngle is undefined and is not an object.
Please help and any suggestion is appreciated.
Thank you.
You may have resolved this problem.
"faces.faces" worked for me..
const faceDetected = (faces) => {
setFaces(faces.faces)
}
I am new to react-native..
So if you resolved it by some other way please let us know.
I believe I have fixed your problem:
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { Camera } from 'expo-camera';
import * as FaceDetector from 'expo-face-detector'
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [faces, setFaces] = useState([])
const faceDetected = ({faces}) => {
setFaces(faces) // instead of setFaces({faces})
console.log({faces})
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission !== true) {
return <Text>No access to camera</Text>
}
return (
//<View style={{ flex: 1 }}>
<Camera
style={{ flex: 1 }}
type='front'
onFacesDetected = {faceDetected}
FaceDetectorSettings = {{
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.all,
runClassifications: FaceDetector.Constants.Classifications.none,
minDetectionInterval: 5000,
tracking: false
}}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
{faces[0] && <Text style= {{top:200}}> is {faces[0].rollAngle} </Text>} // only render text if faces[0] exists
</View>
</Camera>
//</View>
);
}
I think your main problem was you were using
setFaces({faces})
instead of
setFaces(faces)

Redirecting to different scene in React Native

I am creating sign up feature in my React Native app.
I have a touchable highlight in my render:
<TouchableHighlight style={styles.button} onPress={this._handleSignUp}>
<Text style={styles.white_text}>Sign Up</Text>
</TouchableHighlight>
and here is the handleSignUp function:
_handleSignUp: function(){
fetch('https://api.parse.com/1/users', {
method: 'post',
headers: {
'X-Parse-Application-Id': 'MY_ID',
'X-Parse-REST-API-Key': 'MY_KEY',
'X-Parse-Revocable-Session': '1',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
student_id: this.state.id,
password: this.state.password,
})
}).then((response) => response.text())
.then((responseText) => {
if (responseText.code=='201'){
// redirect to Profile Scene
}
});
},
So if user is signed up successfully i want him to be redirected to different scene.
How do we handle this type of redirects in React native?
Use
this.props.navigator.redirect(route)
without props just use this.navigator.redirect(route) instead
You use NavigatorIOS or the lower-level Navigator. See this documentation page for more details:
http://facebook.github.io/react-native/docs/navigator-comparison.html#content
Both Navigator and NavigatorIOS are components that allow you to
manage the navigation in your app between various "scenes" (another
word for screens). They manage a route stack and allow you to pop,
push, and replace states. In this way, they are similar to the html5
history API.
You will have to use NavigationExperiemental for that. That being said, NavigationExperimental is a bit too low level and it's probably much easier to use a 3rd party lib to navigate between your scene components, and to get all the fancy transition animations common to mobile UI patterns. If you are familiar with React Router on the web, I highly encourage you to take a look at React Router Native.
Disclaimer: I'm the author.
The project is hosted on GitHub:
https://github.com/jmurzy/react-router-native
Here's an example that does exactly what you want and more under 80 LOC.
/**
* index.[ios|android].js
*/
import React from 'react';
import {
Header,
Link,
nativeHistory,
Route,
Router,
StackRoute,
withRouter,
} from 'react-router-native';
import {
AppRegistry,
ScrollView,
StyleSheet,
View,
} from 'react-native';
const styles = StyleSheet.create({
component: {
backgroundColor: '#FFFFFF',
flex: 1,
},
home: {
backgroundColor: '#FFFFFF',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
detailCard: {
height: 100,
margin: 20,
width: 100,
},
});
const Master = (props) => (
<View style={styles.component}>
{props.children}
</View>
);
const HomeHeader = withRouter((props) => {
const handleRightButtonPress = () => {
props.router.push('/detail/gray');
};
return (
<Header
{...props}
style={{ backgroundColor: '#26BBE5' }}
title="Feed"
rightButtonText="Gray"
onRightButtonPress={handleRightButtonPress}
/>
);
});
const Home = () => {
const DetailCard = ({ backgroundColor }) => (
<Link to={`/detail/${encodeURIComponent(backgroundColor)}`} style={styles.detailCard}>
<View style={{ flex: 1, backgroundColor }} />
</Link>
);
return (
<ScrollView style={styles.component} contentContainerStyle={styles.home}>
<DetailCard backgroundColor="#EF4E5E" />
<DetailCard backgroundColor="#9498CA" />
<DetailCard backgroundColor="#AFCCB3" />
<DetailCard backgroundColor="#F0D73D" />
<DetailCard backgroundColor="#A176B0" />
<DetailCard backgroundColor="#416BB4" />
<DetailCard backgroundColor="#94B5DC" />
<DetailCard backgroundColor="#D48445" />
</ScrollView>
);
};
const DetailHeader = withRouter((props) => {
const { routeParams } = props;
const title = routeParams.themeColor;
const backgroundColor = routeParams.themeColor;
const colors = ['#EF4E5E', '#D48445', '#AFCCB3', '#F0D73D', '#A176B0'];
const handleRightButtonPress = () => {
const randomIndex = Math.floor(Math.random() * colors.length);
const randomColor = colors[randomIndex];
props.router.push(`/detail/${encodeURIComponent(randomColor)}`);
};
return (
<Header
{...props}
title={title}
style={{ backgroundColor }}
leftButtonText="Back"
rightButtonText="Random"
onRightButtonPress={handleRightButtonPress}
/>
);
});
const Detail = (props) => (
<View style={[styles.component, { backgroundColor: '#FFFFFF' }]}>{props.children}</View>
);
const routes = (
/* Address Bar can be toggled on or off by setting the addressBar prop */
<Router history={nativeHistory} addressBar>
<StackRoute path="master" component={Master}>
<Route path="/" component={Home} overlayComponent={HomeHeader} />
<Route path="/detail/:themeColor" component={Detail} overlayComponent={DetailHeader} />
</StackRoute>
</Router>
);
AppRegistry.registerComponent('YourApp', () => () => routes);
I'm not sure to understand what's the problem here.
Either you redirect to another page then your router will load another component.
Or you can render directly the profile component on success of your request
React.render(, document.getElementById('thedivyouwanttoattachyourcomponent'));
I hope it helps