I am having an issue with my code for my in-app purchases. The use is allowed to buy 'emblems' which should be added to the user through asyncStorage. However this is not the case. Below is all my code and I hope that someone can find a fix. I am currently testing Android only, and the code below is not a final code, but testing code I've been using. They are one time purchases.
This is where I set my API key
const APIKeys = {
google: "*myapikey*",
};
function App() {
useEffect(() => {
Purchases.setDebugLogsEnabled(true);
if (Platform.OS == "android") {
Purchases.configure({ apiKey: APIKeys.google });
}
}, []);
This is the page where everything is supposed to happen:
import * as React from 'react';
import { Button, View, Text, StyleSheet, Image, ScrollView, ImageBackground, TouchableOpacity, Alert} from 'react-native';
import BuyBox from '../components/BuyBox';
import TopBar from '../components/TopBar';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { MaterialIcons } from '#expo/vector-icons';
import Purchases from 'react-native-purchases';
class PremiumScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
offerings: null,
items: null,
emblems: null,
firstCheckpoint: null,
secondCheckpoint: null,
thirdCheckpoint: null,
fourthCheckpoint: null,
fifthCheckpoint: null
};
}
render() {
let outerSize = 0;
let innerSize = 0;
return (
<ImageBackground style={styles.MB} source={require('../../assets/Backgrounds/MainBackground.png')}>
<View style={{flex: 1}}>
<ScrollView contentContainerStyle={{justifyContent: 'center', alignContent: 'center', alignItems: 'center', width: '100%'}}>
<View style={{flexDirection: 'row-reverse', width: '100%', marginHorizontal: 10, right: 8}}>
<TouchableOpacity onPress={() => Alert.alert("Help", "Emblems can be exchanged for three things: First, emblem for a premium trip. Second, two emblems for another save slot. Lastly, one emblem for a cooldown reset")}>
<TopBar />
</TouchableOpacity>
</View>
<Text style={styles.TitleText} onPress={() => console.log(this.state.offerings.emblems.availablePackages)} >Welcome to the Embassy!</Text>
<Text style={styles.SubTitle}>This is where you can purchase Emblems for Premium Trips!</Text>
<View style={{marginVertical: 10}}/>
<View style={{width: 450, height: 450}}>
<ScrollView contentContainerStyle={{justifyContent: 'center', alignContent: 'center', alignItems: 'center'}} horizontal disableIntervalMomentum pagingEnabled>
<BuyBox Price='$0.99' EN='1 Emblems' onPress={async () => {
const products = await Purchases.getProducts(["ispy_1_emblem"]);
const pkg = products.find(product => product.identifier === "ispy_1_emblem");
await Purchases.purchaseProduct(pkg.identifier);
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '1');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 1).toString());
}
})
}}/>
<BuyBox Price='$3.99' EN='5 Emblems' onPress={async () => {
const products = await Purchases.getProducts(["ispy_5_emblem"]);
const pkg = products.find(product => product.identifier === "ispy_5_emblem");
await Purchases.purchaseProduct(pkg.identifier);
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '5');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 5).toString());
}
})
}}/>
<BuyBox Price='$6.99' EN='10 Emblems' onPress={async () => {
const products = await Purchases.getProducts(["ispy_10_emblem"]);
const pkg = products.availablePackages.find(product => product.identifier === "ispy_10_emblem");
await Purchases.purchaseProduct(pkg.identifier);
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '10');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 10).toString());
}
})
}}/>
<BuyBox Price='$12.99' EN='20 Emblems' onPress={async () => {
const products = await Purchases.getProducts(["ispy_20_emblem"]);
const pkg = products.availablePackages.find(product => product.identifier === "ispy_20_emblem");
await Purchases.purchaseProduct(pkg);
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '20');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 20).toString());
}
})
}} />
<BuyBox Price='$24.99' EN='40 Emblems' onPress={async () => {
const products = await Purchases.getProducts();
const pkg = products.availablePackages.find(product => product.identifier === "ispy_20_emblem");
await Purchases.purchaseProduct(pkg);
AsyncStorage.getItem('emblems').then(value => {
if (value == null){
AsyncStorage.setItem('emblems', '20');
} else {
AsyncStorage.setItem('emblems', (Number(value) + 20).toString());
}
})
}}/>
<BuyBox Price='$48.99' EN='80 Emblems' onPress={async () => {
}}/>
</ScrollView>
</View>
<View style={{justifyContent: 'center', alignContent: "center", alignItems: "center", alignSelf: 'center'}}>
<MaterialIcons name="swipe" size={54} color="black" />
</View>
<View style={{margin: '5%'}}/>
<View style={{justifyContent: 'center', alignContent: 'center', alignItems: 'center'}}>
<Text style={styles.SubMain}>Want more information?</Text>
<TouchableOpacity style={{alignContent: 'center', alignItems: 'center', justifyContent: 'center', marginHorizontal: 5}} onPress={() => this.props.navigation.navigate('PrEinfo')}>
<Text style={styles.SubMain2}>Click Here!</Text>
</TouchableOpacity>
</View>
<Text>{this.state.firstCheckpoint}</Text>
<Text>{this.state.secondCheckpoint}</Text>
<Text>{this.state.thirdCheckpoint}</Text>
<Text>{this.state.fourthCheckpoint}</Text>
<Text>{this.state.fifthCheckpoint}</Text>
</ScrollView>
</View>
</ImageBackground>
)
}
}
const styles = StyleSheet.create({
MB: {
flex: 1,
alignContent: 'center',
alignItems: 'center',
justifyContent: 'flex-start',
padding: 5,
paddingTop: 42.5
},
Row:{
flexDirection: 'row',
margin: 10,
marginBottom: 0,
},
TitleText:{
fontSize: 28,
fontWeight: 'bold',
textAlign: 'center'
},
SubTitle:{
fontSize: 16,
textAlign: 'center',
fontWeight: '300'
},
SubMain:{
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center'
},
SubMain2:{
fontSize: 22,
fontWeight: 'bold',
color: 'dodgerblue',
textAlign: 'center'
}
})
export default PremiumScreen;
And this is everything from play console and revenue cat:
Currently, the code on the premiumScreen doesn't work; it doesn't do anything. The onpress does nothing, you see the effect occur, and know the onpress has run however nothing happens. It doesn't crash either.
Some key things to not are that I am testing not an emulator but through the internal testing via the play console. This means I have to do eas build for every change and I cannot see console.logs or try catch. I do have some states I used as checkpoints that are visible at the bottom but when I generally try to set a state to an error, it will normally just crash the app. Any help is appreciated :D
Related
How to make empty input field when props.cityname is changed in react native. setSelectedCountry is holding the selected city name and I want to make it empty when props.cityname value change
import React, {useRef, useState} from 'react';
import {
FlatList,
Image,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
const Test = props => {
const [search, setSearch] = useState('');
const [clicked, setClicked] = useState(false);
const [data, setData] = useState(props.cityNames);
const [selectedCountry, setSelectedCountry] = useState('');
const searchRef = useRef();
const onSearch = search => {
if (search !== '') {
const tempData = data.filter(item => {
return item.value.toLowerCase().indexOf(search.toLowerCase()) > -1;
});
setData(tempData);
} else {
setData(props.cityNames);
}
};
const isFound = data.some(element => {
if (element.value === selectedCountry) {
return true;
}
return false;
});
// React.useEffect(() => {
// setSelectedCountry('');
// }, [isFound]);
return (
<View>
<TouchableOpacity
style={{
paddingHorizontal: 16,
paddingVertical: 20,
borderRadius: 10,
backgroundColor: '#F2F4F7',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}
onPress={() => {
setClicked(!clicked);
}}>
<Text style={{fontWeight: '600'}}>
{selectedCountry == '' ? 'Select Country' : selectedCountry}
</Text>
{clicked ? (
<Image
source={require('./upload.png')}
style={{width: 20, height: 20}}
/>
) : (
<Image
source={require('./dropdown.png')}
style={{width: 20, height: 20}}
/>
)}
</TouchableOpacity>
{clicked ? (
<View
style={{
marginTop: 10,
backgroundColor: '#F2F4F7',
borderRadius: 10,
paddingHorizontal: 0,
paddingVertical: 0,
borderColor: '#F2F4F7',
maxHeight: 300,
}}>
<TextInput
placeholder="Search.."
value={search}
ref={searchRef}
onChangeText={txt => {
onSearch(txt);
setSearch(txt);
}}
style={{
width: '90%',
alignSelf: 'center',
borderWidth: 1,
borderColor: 'white',
borderRadius: 10,
marginTop: 20,
paddingLeft: 16,
}}
/>
<FlatList
nestedScrollEnabled
data={data}
renderItem={({item, index}) => {
return (
<TouchableOpacity
style={{
width: '85%',
alignSelf: 'center',
paddingVertical: 16,
justifyContent: 'center',
}}
onPress={() => {
setSelectedCountry(item.value);
setClicked(!clicked);
onSearch('');
setSearch('');
}}>
<Text style={{fontWeight: '600'}}>{item.value}</Text>
</TouchableOpacity>
);
}}
/>
</View>
) : null}
</View>
);
};
export default Test;
**I want to add max-height so that the dropdown does not go down **
If I removed max-height then it will solve the issues but the length of the dropdown field is large so I need nice solutions
Can you check this snack
just make a little tweaks for ur code
https://snack.expo.dev/#sharqiyem/custom-dropdown
It's scrollable.
I'm using React Native Expo. Currently i'm trying to make an application which uses a barcodescanner for scanning QR-code objects. I've implemented a turn camera button for the front or back camera but when i press the button it does nothing only when i switch from one screen to the other. I think there is something wrong with refreshing the screen immediately but i've no clue of how i should solve this problem
Code:
import React, { useEffect, useState, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert, ActivityIndicator, Pressable } from 'react-native';
import { globalStyles } from '../styles/global';
// import { Camera, BarCodeScanningResult } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BarcodeMask from 'react-native-barcode-mask';
import { useIsFocused, useNavigation } from '#react-navigation/native';
import CustomButton from '../components/CustomButton';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export function ShowLoading(){
return(
<View style={styles.loader}><ActivityIndicator size="large" color='white'/></View>
)
}
export default function Scan(){
const navigation = useNavigation()
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [loading, setLoading] = useState(false);
const [type, setType] = useState(BarCodeScanner.Constants.Type.back);
const isFocused = useIsFocused()
useEffect(() => {
(async () => {
const {status} = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
// useEffect(() => {
// if(loading){
// setLoading(true)
// } else {
// setLoading(false)
// }
// },[loading])
const initScanner = async() => {
const {status} = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
}
const handleNavigation = async() => {
setScanned(false)
navigation.navigate('Oefening')
}
const handleNo = () => {
setScanned(false)
}
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true)
setLoading(true)
setTimeout(() => { Alert.alert(
'QR-Code gevonden',
`QR-Code met type ${type} en data ${data} is gescand, wilt u verder gaan?`,
[
{
text: "Nee",
onPress: () => handleNo(),
},
{
text: "Ja",
onPress: () => handleNavigation(),
}
]
), setLoading(false)}, 1000)
}
if (hasPermission === null) {
return <View style={styles.permissionWrapper}>
<Text style={styles.permissionText}>Een moment geduld..</Text>
<ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator>
</View>;
}
if (hasPermission === false) {
return <Text>Geen toegang tot uw camera!</Text>;
}
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-end'}}>
{loading? (<View style={styles.loader}><ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator></View>
) : (
isFocused &&
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
type={type}
>
<View style={styles.topOptions}>
<View style={styles.cameraRotateWrapper}>
<Pressable style={styles.cameraRotate}
onPress={() => {
setType(
type === BarCodeScanner.Constants.Type.back
? BarCodeScanner.Constants.Type.front
: BarCodeScanner.Constants.Type.back
);
}}
>
<Icon name='rotate-3d-variant' size={40} color={'white'}></Icon>
</Pressable>
</View>
</View>
<BarcodeMask edgeColor={'#62B1F6'} showAnimatedLine={true}/>
</BarCodeScanner>)}
{scanned? <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Gevonden!</Text></View> : <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Zoeken naar QR-Code.... </Text></View>}
{/* {scanned? <Button title={'Opnieuw scannen'} onPress={() => setScanned(false)} /> : null} */}
<View style={styles.bottomOptions}>
<CustomButton textValue="Herladen" onPress={initScanner}></CustomButton>
</View>
</View>
)
}
const styles = StyleSheet.create({
loader: {
justifyContent: "center",
alignItems: 'center',
},
permissionWrapper: {
justifyContent: 'center',
alignItems:'center',
margin: 15,
},
permissionText: {
fontSize: 16,
fontWeight: 'bold',
},
topOptions: {
marginTop: 20,
justifyContent: 'space-between',
marginHorizontal: '10%'
},
searchTextWrapper: {
},
searchText: {
color: 'white',
fontSize: 18,
textAlign: 'center',
},
cameraRotateWrapper: {
width: 50,
height: 50,
},
cameraRotate: {
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderColor: "white",
backgroundColor: '#1f69b1',
borderRadius: 10,
},
bottomOptions: {
marginHorizontal: '10%',
marginBottom: 10,
},
})
In my App I have a screen that normally looks like this
but when I build for production the title wrapper gets pushed down a few pixels, which results in some strange formatting:
I don't really understand why the app looks different when build for release vs when I develop it.
I also tested it on multiple devices but I have the same error on all of them.
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BottomBar from './component/BottomBar';
export default function ScanScreen({ navigation }) {
const [hasPermission, setHasPermission] = useState(null);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
navigation.navigate("Shelf", { shelfID: data.toString() })
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<View style={styles.contentContainer}>
<View style={styles.titleWrapper}>
<Text style={styles.text}> Shelf Scanner </Text>
</View>
<View style={{flex: 1}}>
<BarCodeScanner
onBarCodeScanned={handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
</View>
</View>
<BottomBar navigation={navigation} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
flexDirection: 'row',
},
titleWrapper: {
width: '100%',
top: 30,
height: 50,
alignSelf: 'center',
alignItems: 'center',
backgroundColor: '#A2F5AA',
},
text: {
fontSize: 15,
justifyContent: 'center',
fontWeight: 'bold',
flex: 1,
marginTop: 10,
},
contentContainer: {
flex: 1
},
});
I fixed it by removing top: 30, from titleWrapper. The title is now offset in develop mode, but it at least looks correct in the production build
I'm tried to re-render Flat list but can't be updated anymore,
I'm getting the data from real-time DB and passed to Flatlist as a data props,
and write a function to delete an item from the list and DB and work very well, but when I delete the last one of the list I can not see Empty screen "List" just stock with the last one I've deleted Although it's deleted in DB!
code
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, ScrollView, TouchableOpacity } from 'react-native';
import firebase from "react-native-firebase";
import Icon from 'react-native-vector-icons/Ionicons';
class UserFavorites extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: null,
favorites: [],
}
}
componentDidMount() {
const currentUser = firebase.auth().currentUser.uid;
this.setState({ currentUser });
const favorites = firebase.database().ref(`favorites/${currentUser}`);
favorites.on("value", (snapshot) => {
let favorites = []
snapshot.forEach((childSnapshot) => {
favorites.push({
ProviderId: childSnapshot.val().ProviderId,
providerName: childSnapshot.val().providerName,
providerService: childSnapshot.val().providerService,
});
this.setState({ favorites })
});
});
}
_listEmptyComponent = () => {
return (
<View style={styles.container}>
<Text style={{ alignSelf: "center" }}> No favorites Provider Found :O</Text>
</View>
)
}
render() {
const { fav } = this.state;
return (
<View style={styles.container} >
<FlatList data={this.state.favorites}
key={Math.random() * 1000}
contentContainerStyle={{ flexGrow: 1 }}
ListEmptyComponent={this._listEmptyComponent()}
extraData={this.state}
renderItem={({ item }) => {
return (
<ScrollView>
<TouchableOpacity>
<View
style={{
flex: 1,
paddingLeft: 15,
paddingRight: 10,
height: 105,
alignItems: "center",
backgroundColor: "#fafafa",
flexDirection: "row",
borderBottomWidth: .8,
borderBottomColor: "#aaa"
}}>
<Icon style={{ alignSelf: "center" }} name="ios-contact" size={60} color="#1567d3" />
<View style={{ flex: 1, padding: 5, flexDirection: "row" }}>
<View style={{ marginLeft: 27 }}>
<Text style={{
fontSize: 18,
fontWeight: "800",
fontFamily: 'Gill Sans',
color: '#000',
}}>
{item.providerName}
</Text>
<Text style={{
fontSize: 18,
fontWeight: "800",
fontFamily: 'Gill Sans',
color: '#000',
}}>
{item.providerService}
</Text>
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center", flex: 1 }}>
<Icon style={{ marginRight: 20 }}
name={`ios-heart${fav ? "" : "-empty"}`}
size={35} color="#f00"
onPress={() => {
const currentUser = firebase.auth().currentUser.uid;
firebase.database().ref(`favorites/${currentUser}/${item.ProviderId}`).remove().then(() => alert("Removed"))
}}
/>
</View>
</View>
</View>
</TouchableOpacity>
</ScrollView>
)
}
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default UserFavorites;
You are removing the item from firebase but not from the flatlist's data source this.state.favorites, add a function that'll you call after removing the item from firebase.
_onRemove = (_item) => {
this.setState({
favorites: this.state.favorites.filter(item => item.ProviderId !== _item.ProviderId)
});
}
Pass the item you want to delete to the function in your flatlist
renderItem={({ item }) => {
return ....
//scrollview code
<Icon style={{ marginRight: 20 }}
name={`ios-heart${fav ? "" : "-empty"}`}
size={35} color="#f00"
onPress={() => {
const currentUser = firebase.auth().currentUser.uid;
....
// firebase code
this._onRemove(item);
}
/>
....
//rest of the code
}}
I am trying to follow the example (https://github.com/facebook/react-native/tree/master/Examples/UIExplorer/Navigator) on the react native site to set up my navigator, but I can't seem to get it to work. No matter what I seem to do, the GoogSignIn scene always comes up blank although it does hit both of my console.log points in the file. I have tried switching the starting point to a different scene in my app, but the same thing always happens. I assume this is something I did wrong in index.ios.js with my navigator, but I'm not sure what. Any help is much appreciated.
index.ios.js
'use strict';
var React = require('react-native');
var DataEntry = require('./app/DataEntry');
var PasswordView = require('./app/PasswordView');
var GoogSignIn = require('./app/GoogSignIn');
var {
AppRegistry,
Image,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} = React;
class PasswordRecovery extends React.Component {
render() {
return (
<Navigator
ref={this._setNavigatorRef}
style={styles.container}
initialRoute={{id: 'GoogSignIn', name: 'Index'}}
renderScene={this.renderScene}
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
renderScene(route, navigator) {
switch (route.id) {
case 'GoogSignIn':
return <GoogSignIn navigator={navigator} />;
case 'DataEntry':
return <DataEntry navigator={navigator} />;
case 'PasswordView':
return <PasswordView navigator={navigator} />;
default:
return this.noRoute(navigator);
}
noRoute(navigator) {
return (
<View style={{flex: 1, alignItems: 'stretch', justifyContent: 'center'}}>
<TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}
onPress={() => navigator.pop()}>
<Text style={{color: 'red', fontWeight: 'bold'}}>ERROR: NO ROUTE DETECTED</Text>
</TouchableOpacity>
</View>
);
}
_setNavigatorRef(navigator) {
if (navigator !== this._navigator) {
this._navigator = navigator;
if (navigator) {
var callback = (event) => {
console.log(
`TabBarExample: event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from the owner.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
}
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('PasswordRecovery', () => PasswordRecovery);
I am just trying to get this all setup so that I can display a Google Sign in scene and then navigate from there. The code for that scene so far is here:
GoogSignIn.js
'use strict';
var React = require('react-native');
var { NativeAppEventEmitter } = require('react-native');
var GoogleSignin = require('react-native-google-signin');
var cssVar = require('cssVar');
var { Icon } = require('react-native-icons');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
TouchableHighlight,
PixelRatio,
Navigator,
} = React;
var NavigationBarRouteMapper = {
LeftButton: function(route, navigator, index, navState) {
if (index === 0) {
return null;
}
var previousRoute = navState.routeStack[index - 1];
return (
<TouchableOpacity
onPress={() => navigator.pop()}
style={styles.navBarLeftButton}>
<Text style={[styles.navBarText, styles.navBarButtonText]}>
{previousRoute.title}
</Text>
</TouchableOpacity>
);
},
RightButton: function(route, navigator, index, navState) {
return (
null
);
},
Title: function(route, navigator, index, navState) {
return (
<Text style={[styles.navBarText, styles.navBarTitleText]}>
GOOGLE SIGN IN
</Text>
);
},
};
class GoogSignin extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
componentWillMount() {
var navigator = this.props.navigator;
var callback = (event) => {
console.log(
`NavigationBarSample : event ${event.type}`,
{
route: JSON.stringify(event.data.route),
target: event.target,
type: event.type,
}
);
};
// Observe focus change events from this component.
this._listeners = [
navigator.navigationContext.addListener('willfocus', callback),
navigator.navigationContext.addListener('didfocus', callback),
];
}
componentWillUnmount() {
this._listeners && this._listeners.forEach(listener => listener.remove());
}
componentDidMount() {
this._configureOauth(
'105558473349-7usegucirv10bruohtogd0qtuul3kkhn.apps.googleusercontent.com'
);
}
renderScene(route, navigator) {
console.log("HERE");
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => {this._signIn(); }}>
<View style={{backgroundColor: '#f44336', flexDirection: 'row'}}>
<View style={{padding: 12, borderWidth: 1/2, borderColor: 'transparent', borderRightColor: 'white'}}>
<Icon
name='ion|social-googleplus'
size={24}
color='white'
style={{width: 24, height: 24}}
/>
</View>
<Text style={{color: 'white', padding: 12, marginTop: 2, fontWeight: 'bold'}}>Sign in with Google</Text>
</View>
</TouchableHighlight>
</View>
);
}
render() {
return (
<Navigator
debugOverlay={false}
style={styles.container}
renderScene={this.renderScene}
navigationBar={
<Navigator.NavigationBar
routeMapper={NavigationBarRouteMapper}
style={styles.navBar}/>
}/>
);
}
_configureOauth(clientId, scopes=[]) {
console.log("WE HERE")
GoogleSignin.configure(clientId, scopes);
NativeAppEventEmitter.addListener('googleSignInError', (error) => {
console.log('ERROR signin in', error);
});
NativeAppEventEmitter.addListener('googleSignIn', (user) => {
console.log(user);
this.setState({user: user});
});
return true;
}
_signIn() {
GoogleSignin.signIn();
}
_signOut() {
GoogleSignin.signOut();
this.setState({user: null});
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
messageText: {
fontSize: 17,
fontWeight: '500',
padding: 15,
marginTop: 50,
marginLeft: 15,
},
button: {
backgroundColor: 'white',
padding: 15,
borderBottomWidth: 1 / PixelRatio.get(),
borderBottomColor: '#CDCDCD',
},
buttonText: {
fontSize: 17,
fontWeight: '500',
},
navBar: {
backgroundColor: 'white',
},
navBarText: {
fontSize: 16,
marginVertical: 10,
},
navBarTitleText: {
color: cssVar('fbui-bluegray-60'),
fontWeight: '500',
marginVertical: 9,
},
navBarLeftButton: {
paddingLeft: 10,
},
navBarRightButton: {
paddingRight: 10,
},
navBarButtonText: {
color: cssVar('fbui-accent-blue'),
},
scene: {
flex: 1,
paddingTop: 20,
backgroundColor: '#EAEAEA',
},
});
module.exports = GoogSignin;
edit: screenshots of inspector:
In your renderScene method, try doing something like this (this will also help you remove that big switch):
Component = route.id
<View style={styles.container}>
<Component navigator={navigator} route={route} />
</View>
styles = StyleSheet.create({
container:
flex: 1
})