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.
Related
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.
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
}
});
I was recently working on a React Native project and I choose to use KeyBoardAwareScrollView to handle the keyboard scroll of the screen. The Below image shows the design which should be actual but when I use keyboardAvoidingView it starts to add padding to the bottom of the screen while I want the screen to scroll up when the keyboard is visible, after doing some research I came across the KeyboardAvoidingScrollView but using that if i give they height of
flex: 1
If i change this line to a static height it fixes the issue on a static screen
scrollContainer: { height: 1000 }
to the container that holds the content everything is pushed to the top.
To somehow adjust the view I gave the scroll container fixed height that did solve the problem temporarily but didn't work on all screen sizes.
My Code Looks like this
import {
View,
Text,
StyleSheet,
SafeAreaView,
Image,
StatusBar,
KeyboardAvoidingView,
} from "react-native";
import AuthContent from "../../auth/AuthContent";
import AuthForm from "../../auth/AuthForm";
import CustomTextInput from "../../components/CustomTextInput";
import { setEmailPass } from "../../../redux/UserReucer";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { ImageBackground } from "react-native";
import { GlobalStyles } from "../../../consts/GlobalConsts";
import OrientationLoadingOverlay from "react-native-orientation-loading-overlay";
import { useState } from "react";
import Loading from "../../components/Loading";
import { getAxiosClient } from "../../apis/TallyApi";
import { showAlert } from "../../../utils/Alert";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
const SignUpScreen = ({ navigation }) => {
const dispatch = useDispatch();
const currentUser = useSelector((state) => {
return state.mUser;
});
const [isLoading, setIsLoading] = useState(false);
// console.log("Redux state", currentUser);
async function loginHandler({ email, password }) {
setIsLoading(true);
console.log("Signup Screen", email, password);
try {
let response = await getAxiosClient().post("/users/checkEmail", {
email: email,
});
dispatch(setEmailPass({ email, password }));
navigation.navigate("RoleScreen");
console.log("Axios response ", response.data);
} catch (err) {
// const { response } = err;
// const { request, ...errorObject } = response;
console.log("Axios Error ", err.response.data.message);
showAlert(err.response.data.message);
// console.error(err);
// console.error(err);
} finally {
setIsLoading(false);
}
}
return (
<>
<ImageBackground
source={require("../../../../assets/background_color.png")}
style={GlobalStyles.backgroundContainer}
>
<SafeAreaView style={styles.container}>
<KeyboardAwareScrollView
style={styles.container}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<View style={styles.scrollContainer}>
<StatusBar barStyle="light-content" />
<View style={styles.topSpace}></View>
<View style={styles.mainContainer}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require("../../../../assets/email_icn.png")}
></Image>
</View>
<View style={styles.textContainer}>
<Text style={styles.largeText}>Continue with email</Text>
<Text style={styles.smallText}>
Enter your email address to get register with palace
</Text>
</View>
<View style={styles.authContainer}>
<AuthContent
styles={styles.authContainer}
onAuthenticate={loginHandler}
></AuthContent>
</View>
</View>
<View style={styles.bottomSpace}></View>
<Loading isLoading={isLoading}></Loading>
</View>
</KeyboardAwareScrollView>
</SafeAreaView>
</ImageBackground>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContainer: { flex: 1 },
largeText: {
fontSize: 30,
color: "white",
marginVertical: 9,
textAlign: "center",
},
smallText: {
fontSize: 16,
color: "white",
marginVertical: 9,
textAlign: "center",
},
topSpace: {
flex: 0.5,
},
mainContainer: {
flex: 8.5,
},
bottomSpace: {
flex: 1,
},
imageContainer: {
flex: 3,
alignItems: "center",
justifyContent: "center",
},
textContainer: {
flex: 1.5,
justifyContent: "center",
},
authContainer: {
flex: 2.5,
},
image: {
resizeMode: "contain",
height: "90%",
},
});
export default SignUpScreen;
Just use a <ScrollView> rather than <KeyboardAwareScrollView>
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'
}
});
I am creating a mobile application with React Native and I decided to use a navigation bar that comes from the site 'https://github.com/beefe/react-native-navigation-bar', but I do not know how to use it in my code.
I would like you to send me examples of the navigation bar of the site 'https://github.com/beefe/react-native-navigation-bar'.
This document is clearly shows how to use this component. Just 2 steps:
Install package.
npm install react-native-navigation-bar --save
Import and use. Change attributes the way you like.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import NavigationBar from 'react-native-navigation-bar';
export default class Example extends Component {
render() {
return (
<View>
<NavigationBar
title='Main title'
height={50}
leftButtonTitle='back'
rightButtonTitle='forward'
/>
<Text>ABC</Text>
</View>
);
}
}
I think you should use a plugin: navigationbar-react-native
First, if you use react-navigation you should hide header-bar and use custom header-bar
export const RootStack = createStackNavigator(
{
App: {
screen: AppComponent,
navigationOptions: {
header: null,
},
},
},
{
initialRouteName: 'App',
}
);
1, Install package
npm i navigationbar-react-native --save
2, Using
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,Image,
View,
TouchableOpacity,
} from 'react-native';
import NavigationBar from 'navigationbar-react-native';
const ComponentLeft = () => {
return(
<View style={{ flex: 1, alignItems: 'flex-start'}} >
<TouchableOpacity style={ {justifyContent:'center', flexDirection: 'row'}}>
<Image
source={require('./img/ic_back.png')}
style={{ resizeMode: 'contain', width: 20, height: 20, alignSelf: 'center' }}
/>
<Text style={{ color: 'white', }}>Back Home</Text>
</TouchableOpacity>
</View>
);
};
const ComponentCenter = () => {
return(
<View style={{ flex: 1, }}>
<Image
source={require('./img/ic_logo.png')}
style={{resizeMode: 'contain', width: 200, height: 35, alignSelf: 'center' }}
/>
</View>
);
};
const ComponentRight = () => {
return(
<View style={{ flex: 1, alignItems: 'flex-end', }}>
<TouchableOpacity>
<Text style={{ color: 'white', }}> Right </Text>
</TouchableOpacity>
</View>
);
};
class App extends Component {
render() {
return (
<View style={styles.container}>
<NavigationBar
componentLeft = { () => {<ComponentLeft /> }
componentCenter = { () => {<ComponentCenter /> }
componentRight = { () => {<ComponentRight /> }
navigationBarStyle= {{ backgroundColor: ''#215e79'' }}
statusBarStyle = {{ barStyle: 'light-content', backgroundColor: '#215e79' }}
/>
</View>
);
}
}
Easy create custom header bar in react native