Google login without firebase is not working in react native - react-native

I'm trying to implement google login without firebase in react-native. here i have generated Client ID and Client secret from google cloud and also added required dependency but still the state is not loaded and not showing any content.
I received this error in console: A non-recoverable sign in failure occurred
please help me if anyone is having idea about it
Thanks in advance!!
import {Text, View, Image} from 'react-native';
import React, {Component} from 'react';
import {GoogleSignin, statusCodes} from '#react-native-community/google-signin';
import {GoogleSigninButton} from '#react-native-community/google-signin';
export class GoogleLogin extends Component {
constructor(props) {
super(props);
this.state = {
userGoogleInfo: {},
loaded: false,
};
}
componentDidMount() {
GoogleSignin.configure({
webClientId:
'my Web client id',
offlineAccess: true,
});
}
signIn = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
this.setState({
userGoogleInfo: userInfo,
loaded: true,
});
console.log(this.state.userGoogleInfo);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log('e 1');
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log('e 2');
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log('e 3');
} else {
console.log(error.message);
}
}
};
render() {
return (
<View>
<GoogleSigninButton
onPress={this.signIn}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
style={{width: '100%', height: 100}}
/>
{this.state.loaded ? (
<View>
<Text> {this.state.userGoogleInfo.dictionary}</Text>
console.log('Hello')
</View>
) : (
<Text> Not sign in</Text>
)}
</View>
);
}
}
export default GoogleLogin;

Related

Failed to start signInAsync as concurrent GoogleSignIn task

I have an app that I'm using to sign in into google with the expo-google-sign-in library. However, I'm getting the following error:
Error: Failed to start signInAsync as a concurrent GoogleSignIn task is already running
promiseMethodWrapper#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:2864:45
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:100167:40
invokeAuthMethod$#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:157126:80
tryCatch#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29230:23
invoke#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29403:32
tryCatch#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29230:23
invoke#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29303:30
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29313:21
tryCallOne#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:4064:16
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:4165:27
_callTimer#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:31253:17
_callImmediatesPass#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:31292:17
callImmediates#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:31509:33
__callImmediates#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:3358:35
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:3144:34
__guard#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:3341:15
flushedQueue#http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:3143:21
flushedQueue#[native code]
callFunctionReturnFlushedQueue#[native code]
Here's the code:
import * as React from 'react';
import { useEffect } from 'react';
import { StyleSheet, Image, Pressable, ImageBackground } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import * as GoogleSignIn from 'expo-google-sign-in';
export default function TabTwoScreen() {
// useEffect(async function () {
// try {
// console.log("running initAsync")
// await GoogleSignIn.initAsync({
// // You may ommit the clientId when the firebase `googleServicesFile` is configured
// clientId: '435403173197-1ofadf8gflla92ibd6ibveb4tvv1vice.apps.googleusercontent.com',
// // Provide other custom options...
// });
// } catch ({ message }) {
// alert('GoogleSignIn.initAsync(): ' + message);
// }
// }, []);
return (
<View style={styles.container}>
<ImageBackground source={require(
"../assets/images/happy-tiny-people-listening-spiritual-music/5870.jpg")}
style={styles.background}>
<Pressable onPress= {() => {
console.log("running sign in async");
GoogleSignIn.signInAsync();
}}
style={({ pressed }) => [{
backgroundColor: pressed ? 'white' : '#03befc'
},
styles.google]}>
<Image source={require("../assets/google_signin.png")} style={styles.googleImage}/>
<Text style={styles.googleText}>Sign In With Google</Text>
</Pressable>
</ImageBackground>
</View>
);
}
What am I doing wrong and how to fix this error? I expect there to be no error and that the google sign in to happen. The error occurs when the perusable is pressed.
This might help
const signInAsync = async () => {
try {
await GoogleSignIn.askForPlayServicesAsync();
const { type, user } = await GoogleSignIn.signInAsync();
if (type === 'success') {
// success
}
} catch ({ message }) {
alert('login: Error:' + message);
}
};
<Pressable onPress= {() => { signInAsync() }
More detail here sdk/google-sign-in/

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);
}, []);

React native Printer

I'm new to react-native, I'm making app which can connect to printer with bluetooth I'm using react-native-ble-plx . I had successfully connect to my printer with bluetooth but I don't know to to print some thing from it.
import React, {PureComponent} from 'react';
import {View, Text, Button} from 'react-native';
import {BleManager} from 'react-native-ble-plx';
export default class App extends PureComponent {
constructor(props) {
super(props);
this.state = {};
this.manager = new BleManager();
}
componentDidMount() {
const subscription = this.manager.onStateChange(state => {
if (state === 'PoweredOn') {
console.log(state);
this.scanAndConnect();
}
}, true);
}
scanAndConnect() {
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
// Handle error (scanning will be stopped automatically)
console.log(error);
}
// if (device) {
// console.log(device);
// }
if (device.name === 'POSTEK061F') {
// Stop scanning as it's not necessary if you are scanning for one device.
this.manager.stopDeviceScan();
device
.connect()
.then(device => {
return device.discoverAllServicesAndCharacteristics();
})
.then(device => {
// Do work on device with services and characteristics
console.log(device.name);
console.log(device);
})
.catch(error => {
// Handle errors
});
// Proceed with connection.
}
});
}
async printHTML() {
//print something
}
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Button onPress={this.printHTML} title="Print HTML" />
</View>
);
}
}
when user click on print button it should print some thing.

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)
);
};

What is the best way to deal with empty error message in react native?

I have to display a error message called "No record available".
This is my scenario : -
API Call {
if (data){
loading == false
}
}
In my component
Render(){
{
data.length > 0 && this.state.loading == false ?
<Flat List/>
: null
}
{
data.length==0 ?
<Text>No Record found</Text>
: null
}
}
My Problem was , my message displays if data not found but it doesn't refresh.
I have to achieve a scenario like this -
when i open or navigate through a page then its first show blank then loader start and after API call if data not found then they display a message.
This is a working example of what you describe. When the component loads the data is empty until your API call runs in componentDidMount. I have emulated the API call with a timeout of 2 seconds. You need to switch out the setTimeout function in apiCall with your own fetch method and set the state in the callback of that function
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class Test extends Component {
state = {
loading: false,
data: [],
};
componentDidMount() {
this.apiCall();
}
apiCall = () => {
this.setState({ loading: true });
setTimeout(() => {
this.setState({
loading: false,
data: ['1', '2', '3'],
});
}, 3000);
};
render() {
if (this.state.loading) return <Text>Loading...</Text>;
if (this.state.data.length === 0) return <Text>No records found</Text>;
return (
<View>
<Text>Records found</Text>
</View>
);
}
}
export default Test;
You can bind your action and reducers data
here this is the example you want
import React, { Component } from 'react';
import {
Text,
View,
Dimensions,
FlatList,
ScrollView,
} from 'react-native';
import { connect } from 'react-redux';
import {showLoading, getProducts} from '../actions/productAction';
import * as Progress from 'react-native-progress';
class Data extends Component {
this.state = {
product: [],
loading: false
};
componentWillMount() {
this.setState({loading: true});
API CALL();
}
render() {
return (
<View>
{this.state.isLoading ?
<View>
<Progress.CircleSnail thickness={5} size={55} color={['#000000', '#000000', '#FFFFFF',]} />
</View>
:
null
}
{this.state.product.length === 0 && <View>
<Text>{"NO PRODUCT"}</Text>
</View>}
<FlatList
data={this.state.product}
/>
</View>
);
}
}
export default Data;