TypeError: undefined is not an object (evaluating '_firebase.database.ref') - firebase

I get this error :
"TypeError: undefined is not an object (evaluating '_firebase.database.ref')"
I don't understand why this error is happening.
This is the code:
import { useNavigation } from '#react-navigation/core'
import React, { useState } from 'react'
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import { auth, database } from '../firebase'
const HomeScreen = () => {
const navigation = useNavigation()
const [led1Status, setLed1Status] = useState("1")
const handleSignOut = () => {
auth
.signOut()
.then(() => {
navigation.replace("Login")
})
.catch(error => alert(error.message))
}
const handleLed1Toggle = () => {
const firebaseRef = database.ref().child("Led1Status")
if (led1Status === "1") {
firebaseRef.set("0")
setLed1Status("0")
} else {
firebaseRef.set("1")
setLed1Status("1")
}
}
return (
<><View style={styles.container}>
<Text>Email: {auth.currentUser?.email}</Text>
<TouchableOpacity
onPress={handleSignOut}
style={styles.button}
>
<Text style={styles.buttonText}>Sign out</Text>
</TouchableOpacity>
</View>
<View style={styles.bruhst}>
<TouchableOpacity
onPress={handleLed1Toggle}
style={[styles.button, styles.buttonOutline]}
>
<Text style={styles.buttonOutlineText}>Say it</Text>
</TouchableOpacity>
</View></>
)
}
export default HomeScreen
const styles = StyleSheet.create({
bruhst: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
container: {
flex: 1,
marginTop: 30,
marginLeft: 20,
},
button: {
backgroundColor: '#F2ACB9',
width: '50%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
marginTop: 15,
},
buttonText: {
color: 'white',
fontWeight: '700',
fontSize: 16,
},
buttonOutline: {
backgroundColor: 'white',
},
buttonOutlineText: {
color: '#F2ACB9',
fontWeight:'700',
fontSize: 16,
},
})
I am working on a mobile app with a button. im trying to make the button 'Say it' when pressed to change the value of the key from the realtime database from firebase from a 0 to a 1. the key name on the realtie database is Led1Status.

Related

Could anyone help me to write code to upload image to the firestore database with url below is my code to upload image with form

I couldn't find a way to upload image to the firestore database with url while I am submitting the I am getting the file path like file:///data/user/0/com.kk/cache/rn_image_picker_lib_temp_6e973dbe-ab8f, but I need to get file path with url in firestore. Could anyone help with this?. Below is my code to upload image with form.
import React, { useState } from "react";
import { View,StyleSheet,Text, ScrollView, Pressable, Image, TextInput } from 'react-native';
import { Button } from "react-native-elements";
import {firebase} from '#react-native-firebase/firestore';
import { launchImageLibrary } from "react-native-image-picker";
export default function Test(){
const [username,setusername] = useState('');
const [email,setemail] = useState('');
const[imageURI,setImageURI] = useState(null);
const handleOpenLibrary = async () => {
let options = {
mediaType: "photo",
};
const imageData = await launchImageLibrary(options);
setImageURI(imageData.assets[0].uri);
};
function create(){
firebase.firestore()
.collection('Actors')
.add({
name: username,
email: email,
image: {uri:imageURI},
}).then(() => {
console.log("data submitted");
}).catch((error)=> {
console.log(error);
});;
} return (
<View style={styles.body}>
<View style={styles.row}>
<TextInput
style={{backgroundColor:'white'}}
value={username}
onChangeText= {(username) => {setusername(username)}}
placeholder="Enter name"/>
</View>
<View style={styles.row}>
<TextInput
style={{backgroundColor:'white'}}
value={email}
onChangeText= {(email) => {setemail(email)}}
placeholder="Enter email"/>
</View>
<View style={styles.imageContainer}>
<Image
source={{uri:imageURI}}
style={styles.imageBox}
resizeMode='contain'
/>
</View>
<Button
title="submit"
onPress={create}/>
<Button title="pick" onPress={handleOpenLibrary}/>
</View>
)}
const styles = StyleSheet.create({
body: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
alignItems: 'center',
justifyContent: 'flex-start',
},
text: {
fontSize: 40,
margin: 10,
},
row: {
flexDirection: 'row',
alignItems: 'flex-start',
justifyContent:'space-between',
},
footer: {
position: 'absolute',
flex:0.1,
left: 0,
right: 0,
bottom: -10,
flexDirection:'row',
height:50,
alignItems:'center',
justifyContent:'center',
borderRadius:10,
},
footerText: {
color:'white',
fontWeight:'bold',
alignItems:'center',
fontSize:18,
},
imageContainer: {
marginVertical: 20,
borderWidth: 5,
borderColor: '#ff5555'
},
imageBox: {
width: 256,
height: 256
}
});

TypeError: undefined is not an object on react native app

the code below of my react native app needs to display a simple background image to do that I use in below code (I use css and js), when I run the code I get the following error, it tells me the width parameter is not defined though it is how do I solve this?
Error Width React Native:
:19 in handleException
at node_modules/react-native/Libraries/Core/ReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modules/react-native/Libraries/ReactNative/renderApplication.js:54:4 in renderApplication
at node_modules/react-native/Libraries/ReactNative/AppRegistry.js:117:25 in runnables.appKey.run
at node_modules/react-native/Libraries/ReactNative/AppRegistry.js:213:4 in runApplication
TypeError: undefined is not an object (evaluating 'style.width')
This error is located at:
TypeError: undefined is not an object (evaluating 'style.width')
This error is located at:
in NavigationContainer (at Router.js:101)
in App (at Router.js:127)
in Router (at App.js:8)
in App (created by ExpoRoot)
in ExpoRoot (at renderApplication.js:45)
in RCTView (at View.js:34)
in View (at AppContainer.js:106)
in DevAppContainer (at AppContainer.js:121)
in RCTView (at View.js:34)
in View (at AppContainer.js:132)
in AppContainer (at renderApplication.js:39)
React Code:
/* eslint-disable class-methods-use-this */
/* eslint-disable global-require */
/* eslint-disable react/destructuring-assignment */
import * as React from 'react';
import {
SafeAreaView,
ImageBackground,
Button,
TextInput,
View
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { login } from '../services/user';
import * as style from './style/design';
class Login extends React.Component {
constructor() {
super();
this.state = {
username: '',
password: ''
};
}
async login() {
const ret = await login(this.state.username, this.state.password);
if (ret === 'denied') {
console.log(`Sono dentro con : ${ret.toString()}`);
} else {
Actions.home();
}
}
gotoregister() {
Actions.register();
}
render() {
return (
<View style={style.container}>
<ImageBackground
source="../assets/images/backgroundhome.jpg"
style={style.imgBackground}
>
<SafeAreaView>
<TextInput
style={style.textinput}
onChangeText={(text) => {
this.setState({ username: text });
}}
value={this.state.username}
placeholder="insert username"
/>
<TextInput
style={style.textinput}
onChangeText={(text) => {
this.setState({ password: text });
}}
value={this.state.password}
placeholder="insert password"
/>
<Button title="Login" onPress={() => this.login()} />
<Button
title="Register to fit"
onPress={() => this.gotoregister()}
/>
</SafeAreaView>
</ImageBackground>
</View>
);
}
}
export default Login;
design.js file:
import { StyleSheet } from 'react-native';
export const styles = StyleSheet.create({
container: { alignItems: 'center', flex: 1, justifyContent: 'center' }
});
export const style = StyleSheet.create({
image: {
height: 100,
width: 260
},
imgBackground: {
flex: 1,
height: '100%',
width: '100%'
},
textinput: {
backgroundColor: '#FFFFFF',
borderColor: '#D3D3D3',
borderRadius: 20,
borderWidth: 2,
height: 50,
marginTop: 10,
textAlign: 'center'
}
});
style.container is undefined. Try merging the styles in the design.js file.
export const style = StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center'
},
image: {
height: 100,
width: 260
},
imgBackground: {
flex: 1,
height: '100%',
width: '100%'
},
textinput: {
backgroundColor: '#FFFFFF',
borderColor: '#D3D3D3',
borderRadius: 20,
borderWidth: 2,
height: 50,
marginTop: 10,
textAlign: 'center'
}
});

Advice need for React Navigation auth flow structure

Trying out react navigation v5 so I created a login register form that brings the user to the dashboard if he's logged in before using AsyncStorage. It works fine but I would like to know how to improve on the structure of code. Currently, I put all the components in a stack navigator, but things might get messy if I were to add more screens. Also, I would be switching to hooks but am confused if and how I should apply useContext useMemo useEffect
App.js file
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Login from './components/login';
import Signup from './components/signup';
import Dashboard from './components/dashboard';
import AuthLoading from './components/authLoading'
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator
initialRouteName="AuthLoading"
screenOptions={{
headerTitleAlign: 'center',
headerStyle: {
backgroundColor: '#3740FE',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}>
<Stack.Screen
name="AuthLoading"
component={AuthLoading}
options={
{title: 'AuthLoading'},
{headerLeft:null}
}/>
<Stack.Screen
name="Signup"
component={Signup}
options={{ title: 'Signup' }}
/>
<Stack.Screen
name="Login"
component={Login}
options={
{ title: 'Login' },
{ headerLeft: null }
}
/>
<Stack.Screen
name="Dashboard"
component={Dashboard}
options={
{ title: 'Dashboard' },
{ headerLeft: null }
}
/>
</Stack.Navigator>
);
}
export default function App() {
return (
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
authLoading.js file
import React from 'react';
import { ActivityIndicator, StatusBar, StyleSheet, View, Text } from 'react-native';
import {AsyncStorage} from 'react-native'
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this.checkUserToken();
}
async checkUserToken() {
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
console.log(isLoggedIn)
// If User Token
if (isLoggedIn === '1') {
//AsyncStorage.setItem(isLoggedIn);
this.props.navigation.navigate('Dashboard');
}
else {
this.props.navigation.navigate('Login');
}
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>Checking Authentication</Text>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#CA3433',
justifyContent: 'center',
alignItems: 'center',
},
text: {
justifyContent: 'center',
color: '#fff',
fontSize: 18,
fontWeight: '500',
},
});
signup.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
export default class Signup extends Component {
constructor() {
super();
this.state = {
displayName: '',
email: '',
password: '',
isLoading: false
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
registerUser = () => {
if (this.state.email === '' && this.state.password === '') {
Alert.alert('Enter details to signup!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
res.user.updateProfile({
displayName: this.state.displayName
})
console.log('User registered successfully!')
this.setState({
isLoading: false,
displayName: '',
email: '',
password: ''
})
this.props.navigation.navigate('Login')
})
.catch(error => this.setState({
isLoading: false,
errorMessage: error.message
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Name"
value={this.state.displayName}
onChangeText={(val) => this.updateInputVal(val, 'displayName')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signup"
onPress={() => this.registerUser()}
/>
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Login')}>
Already Registered? Click here to login
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
login.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
import {AsyncStorage} from 'react-native';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
isLoading: false,
errorMessage: ''
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
/**
*
*/
userLogin = () => {
if (this.state.email === '' && this.state.password === '') {
this.setState({
errorMessage: "Enter details to sign in"
})
//Alert.alert('Enter details to signin!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
console.log(res)
console.log('User logged-in successfully!')
this.setState({
isLoading: false,
email: '',
password: ''
})
AsyncStorage.setItem('isLoggedIn', '1')
this.props.navigation.navigate('Dashboard')
})
.catch(error => this.setState({
errorMessage: 'Wrong email/password',
isLoading: false
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signin"
onPress={() => this.userLogin()}
/>
{/* style this */}
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Signup')}>
Don't have account? Click here to signup
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
dashboard.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
import {AsyncStorage} from 'react-native';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
isLoading: false,
errorMessage: ''
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
/**
*
*/
userLogin = () => {
if (this.state.email === '' && this.state.password === '') {
this.setState({
errorMessage: "Enter details to sign in"
})
//Alert.alert('Enter details to signin!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
console.log(res)
console.log('User logged-in successfully!')
this.setState({
isLoading: false,
email: '',
password: ''
})
AsyncStorage.setItem('isLoggedIn', '1')
this.props.navigation.navigate('Dashboard')
})
.catch(error => this.setState({
errorMessage: 'Wrong email/password',
isLoading: false
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signin"
onPress={() => this.userLogin()}
/>
{/* style this */}
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Signup')}>
Don't have account? Click here to signup
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
React-Navigation provided help regarding the auth flow on their official site. Just follow the below link
https://reactnavigation.org/docs/auth-flow/
Note: You can follow this article for authentication flow using hooks and react-navigation 5
https://dev.to/embeddednature/create-an-authorization-flow-with-react-navigation-5-x-2pkh

React WebkitAppRegion Warnings

Ok, so I'm extremely new to react, so sorry if this question is really dumb.
I've been working on a react application using electron and expo, and don't fully understand how to solve this warning which is showing in my developer console.
Warning: Failed prop type: Invalid props.style key `WebkitAppRegion` supplied to `View`.
Bad object: {
"display": "flex",
"flexDirection": "row",
"height": 20,
"backgroundColor": "#0e0e11",
"margin": 0,
"borderBottomWidth": 0.5,
"borderColor": "#060607",
"WebkitAppRegion": "drag"
}
When I originally built the design for this UI, I did so with standard html and SCSS, and now I'm attempting to change it to react as my first big project. So having done some googling, I found the information that to include my -webkit-app-region: drag all I needed to do was CammelCase and remove the "-"'s. Except it's now throwing this error, it does the function as intended but how does one solve the "invalid props style" issue?
Some shitty code for ya to critique xD
//app.tsx
import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { SplashScreen } from 'expo';
import * as Font from 'expo-font';
import * as styles from './assets/styles/main'
SplashScreen.preventAutoHide();
setTimeout(SplashScreen.hide, 10000);
export default class App extends React.Component {
state = {
fontLoaded: false,
};
async componentDidMount() {
await Font.loadAsync(styles.fontList);
this.setState({ fontLoaded: true });
}
render() {
return (
this.state.fontLoaded ? (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'stretch', backgroundColor: styles.colors.dark1 }}>
<this.DisplayHandles />
</View>
) : null
);
}
DisplayHandles() {
if (Platform.OS === 'web' && process.versions.electron) {
return ([
<View style={[styles.electron.header, {WebkitAppRegion: 'drag'}]}>
<View style={styles.electron.titleContainer}>
<Text key='title' style={[styles.electron.title, {WebkitAppRegion: 'no-drag', 'userSelect': 'none'}]}> Smartcloud</Text>
</View>
<View style={styles.electron.controlContainer}>
<Text key='minimize' style={[styles.electron.button, {WebkitAppRegion: 'no-drag', 'userSelect': 'none'}]} onClick={handleClick}>-</Text>
<Text key='maximize' style={[styles.electron.button, {WebkitAppRegion: 'no-drag', 'userSelect': 'none'}]} onClick={handleClick}>+</Text>
<Text key='close' style={[styles.electron.button, {WebkitAppRegion: 'no-drag', 'userSelect': 'none'}]} onClick={handleClick}>x</Text>
</View>
</View>,
<View style={{ flex: 1}}>
<Content.CreateHandles />
</View>
]
)
}
return <Content.Container/>
}
}
function handleClick(e) {
e.preventDefault();
console.log('I was clicked')
}
class Content {
static CreateHandles() {
return (
<View>
<Content.Container />
</View>
)
}
static Container () {
return (
<View style={{alignItems: 'center',}}>
<Content.TestingText />
</View>
)
}
static TestingText() {
if (Platform.OS === 'web') {
if (process.versions.electron) {
return (<Text style={{fontSize: 60, color: styles.colors.light5, fontFamily: styles.rubik.medium} }> This is a Electron {process.versions.electron} + {Platform.OS} version </Text>)
}
return (<Text style={{fontSize: 60, color: styles.colors.light5, fontFamily: styles.rubik.medium}}> This is a {Platform.OS} version </Text>)
}
return <Text style={{fontSize: 20, color: styles.colors.light5, fontFamily: styles.rubik.medium}}> This is a {Platform.OS} version</Text>
}
}
// ./assets/styles/main.tsx
export const electron = StyleSheet.create({
header: {
display: 'flex',
flexDirection: 'row',
height: 20,
backgroundColor: colors.dark4,
margin: 0,
borderBottomWidth: 0.5,
borderColor: colors.dark5,
},
titleContainer: {
display: 'flex',
alignItems: 'flex-start',
flexGrow: 1,
},
controlContainer: {
display: 'flex',
justifyContent: 'flex-end',
flexDirection: 'row',
alignItems: 'center',
},
title: {
color: colors.purple,
margin: 0,
marginLeft: 10,
fontSize: 14,
fontFamily: rubik.black,
},
button: {
width: 25,
margin: 0,
marginLeft: 10,
color: colors.purple,
textAlign: 'center',
fontSize: 14,
fontFamily: rubik.black,
}
})

How can I switch firebase configuration using toggle in react native

I am using reactnative, redux and firebase.
Now i want to config two diff firebase env one is development and other one is production.
I implemented a toggle to switch the firebase diff account.
i put firebase config file in ./App.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import firebase from 'firebase';
import store from './src/config/store';
import AppNavigation from './src/navigation';
class App extends Component {
componentWillMount() {
firebase.initializeApp({
apiKey: 'AIzaSyAandJABqieT3fXk2palvAgbYz5B8y9EsM',
authDomain: 'practiciaappsubu.firebaseapp.com',
databaseURL: 'https://practiciaappsubu.firebaseio.com',
projectId: 'practiciaappsubu',
storageBucket: 'practiciaappsubu.appspot.com',
messagingSenderId: '753143230840'
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('logged In');
} else {
console.log('not looged in');
}
});
}
render() {
return (
<Provider store={store}>
<AppNavigation />
</Provider>
);
}
}
export default App;
The toggle is there is Home component. So, after change the toggle from Home componet, how can i get the toggle status in ./App.js file?
The Home.js (component)
import React, { Component } from 'react';
import {
Text,
View,
Image,
ScrollView,
Switch
} from 'react-native';
import { connect } from 'react-redux';
import { NavigationActions } from 'react-navigation';
import { Button, Section } from './helpers';
import { userType } from '../config/MasterData';
import { firebaseEnvAction } from '../actions/HomeAction';
class Home extends Component {
static navigationOptions = {
title: '.: Practicia :.'
};
onPressSignupAs(userInfo) {
// Navigate to sign up page with the user information
console.log(userInfo);
}
onPressLogin() {
// Navigate to login page
const navigateToLogin = NavigationActions.navigate({
routeName: 'login',
params: {}
});
this.props.navigation.dispatch(navigateToLogin);
}
firebaseEnv(val) {
this.props.firebaseEnvAction(val);
}
render() {
return (
<ScrollView contentContainerStyle={styles.contentContainer}>
<View style={styles.container}>
<View style={styles.logoContainer}>
<Image
style={styles.logo}
source={require('../assets/images/logo.png')}
/>
</View>
<View style={styles.contentArea}>
<Text style={styles.signInAs}>Sign Up As...</Text>
<Section>
<Button
onPress={this.onPressSignupAs.bind(this, userType.teacher)}
>
{userType.teacher.showText}
</Button>
</Section>
<Section>
<Button
onPress={this.onPressSignupAs.bind(this, userType.parent)}
>{userType.parent.showText}</Button>
</Section>
<Section>
<Button
onPress={this.onPressSignupAs.bind(this, userType.student)}
>
{userType.student.showText}
</Button>
</Section>
</View>
<View style={styles.LoginBox}>
<Text style={styles.LoginText}>Already have an account? </Text>
<Section>
<Button
style={styles.buttonLogin}
styleText={styles.buttonText}
onPress={this.onPressLogin.bind(this)}
>
Login
</Button>
</Section>
<Section>
<Text style={styles.firebaseText}>Firebase:
<Switch
value={this.props.HomeReducer.firebaseToggle}
onValueChange={(val) => this.firebaseEnv(val)}
disabled={false}
activeText={'Prod'}
inActiveText={'Dev'}
circleSize={30}
barHeight={1}
circleBorderWidth={3}
backgroundActive={'green'}
backgroundInactive={'gray'}
circleActiveColor={'#30a566'}
circleInActiveColor={'#000000'}
/>
</Text>
</Section>
</View>
</View>
</ScrollView>
);
}
}
const styles = {
firebaseText: {
fontSize: 20
},
contentContainer: {
flex: 1
},
container: {
backgroundColor: '#FFFFFF',
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#9DDAEE',
flex: 1,
padding: 10,
justifyContent: 'center',
},
userType: {
fontSize: 23,
fontWeight: 'bold',
backgroundColor: '#3BAFDA',
margin: 10,
padding: 10,
textAlign: 'center',
color: '#fff',
},
contentArea: {
marginLeft: 40,
marginRight: 40,
marginBottom: 20,
},
logoContainer: {
justifyContent: 'center',
alignItems: 'center',
marginTop: 10,
marginBottom: 40,
},
logo: {
width: 250,
height: 75,
},
signInAs: {
fontSize: 20,
textAlign: 'center',
marginBottom: 10,
},
LoginBox: {
marginTop: 20,
marginLeft: 40,
marginRight: 40,
},
LoginText: {
fontSize: 15,
textAlign: 'center',
marginBottom: 10,
},
buttonLogin: {
backgroundColor: '#C4C4C4',
},
buttonText: {
color: '#000000',
}
};
const mapStateToProps = (state) => {
return state;
};
const mapDispatchToProps = {
firebaseEnvAction
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);
You'll want to dispatch an action when the switch is toggled that tears down your firebase instance (firebase.initializeApp({...});) and initializes a new firebase app with the credentials you want. This means you'll probably want to dispatch a new initilizeFirebase action in your App.js componentWillMount function. Then your Home.js should pull the configured firebase instance from the store. This also means you'll probably want to keep your firebase instance in the store as well.

Resources