Skip to content

Instantly share code, notes, and snippets.

@dwijonarko
Last active April 15, 2019 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwijonarko/93518458d7cc061263488e82701655bf to your computer and use it in GitHub Desktop.
Save dwijonarko/93518458d7cc061263488e82701655bf to your computer and use it in GitHub Desktop.
Firebase Auth with react-native
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import firebase from "firebase";
import AuthLoadingScreen from "./components/AuthLoadingScreen";
import SignInScreen from "./components/LoginPage";
import HomeScreen from "./components/HomeScreen";
import OtherScreen from "./components/OtherScreen";
import { createSwitchNavigator, createStackNavigator, createAppContainer } from 'react-navigation';
// Implementation of HomeScreen, OtherScreen, SignInScreen, AuthLoadingScreen
// goes here.
const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen }, { headerMode: 'none' });
const AppContaner = createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
));
export default class App extends React.Component {
//sesuaikan dengan project firebase masing-masing
componentWillMount() {
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx"
});
}
render() {
return (
<AppContaner />
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
import React, { Component } from 'react';
import { View, ActivityIndicator,StatusBar,AsyncStorage } from 'react-native';
export default class AuthLoadingScreen extends Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
// Fetch the token from storage then navigate to our appropriate place
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
// Render any loading content that you like here
render() {
return (
<View>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
import React from "react";
import {View,Button,AsyncStorage} from 'react-native'
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome to the app!',
};
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}>
<Button title="Show me more of the app" onPress={this._showMoreApp} />
<Button title="Actually, sign me out :)" onPress={this._signOutAsync} />
</View>
);
}
_showMoreApp = () => {
this.props.navigation.navigate('Other');
};
_signOutAsync = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate('Auth');
};
}
import React from 'react';
import { Alert, StyleSheet,ScrollView, View, Image, TextInput, Button,AsyncStorage,Text } from "react-native";
import firebase from "firebase";
import Spinner from "./Spinner";
export default class LoginPage extends React.Component {
constructor(props) {
super(props)
this.state = { email: '', password: '', error: '', success: '', loading: false };
}
_onPressLogin = () => {
this.setState({ error: '', loading: true });
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(async data => {
this.setState({ error: '', success: 'Authentication success!', loading: false });
this.props.navigation.navigate('App');
console.log(data.user)
await AsyncStorage.setItem('userToken', data.user.accessToken);
})
.catch(e => {
console.log(e)
this.setState({ error: 'Authentication failed.', success: '', loading: false });
});
}
_onPressCancel = () => {
this.setState({ email: '' })
this.setState({ password: '' })
this.setState({ error: '', success: '', loading: false });
}
renderButtonOrSpinner() {
if (this.state.loading) {
return <Spinner />;
}
return <Button onPress={this._onPressLogin.bind(this)} title="Log in" />;
}
render() {
return (
<View style={styles.container}>
<Image source={require('../assets/icon.png')} style={styles.image}></Image>
<Text style={styles.errorTextStyle}>{this.state.error}</Text>
<Text style={styles.successTextStyle}>{this.state.success}</Text>
<TextInput
value={this.state.email}
onChangeText={(inputan) => this.setState({ email: inputan })}
style={styles.email} placeholder="email..."></TextInput>
<TextInput
value={this.state.password}
onChangeText={(inputan) => this.setState({ password: inputan })}
style={styles.email} placeholder="Password,,," secureTextEntry={true}></TextInput>
<View style={styles.button}>
{this.renderButtonOrSpinner()}
</View>
<View style={styles.button}>
<Button
onPress={this._onPressCancel}
title="Cancel"></Button>
</View>
</View>
)
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'skyblue'
},
image: {
width: 120,
height: 120,
marginBottom: 40,
},
email: {
backgroundColor: 'white',
borderRadius: 5,
width: '90%',
padding: 5,
marginBottom: 10,
},
button: {
width: '90%',
marginBottom: 10,
},
errorTextStyle: {
color: '#E64A19',
alignSelf: 'center',
paddingTop: 10,
paddingBottom: 10,
fontWeight: 'bold',
},
successTextStyle: {
color: '#33691e',
alignSelf: 'center',
paddingTop: 10,
paddingBottom: 10,
fontWeight: 'bold',
}
});
import React, { Component } from 'react'
import { Text, View,AsyncStorage,Button } from 'react-native'
export default class OtherScreen extends Component {
_signOutAsync = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate('Auth');
};
render() {
return (
<View style={{flex:1,justifyContent:'center',alignItems: 'center',}}>
<Text> textInComponent </Text>
<Button title="Actually, sign me out :)" onPress={this._signOutAsync} />
</View>
)
}
}
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native';
export default class Spinner extends Component {
render() {
return (
<ActivityIndicator></ActivityIndicator>
);
}
}
import React from "react";
import {KeyboardAvoidingView,View,Button,Text,TextInput,Alert,Image} from 'react-native'
import firebase from "firebase";
import Spinner from "./Spinner";
export default class HomeScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
name:null,
email:null,
photoUrl:null
}
}
componentDidMount() {
this._getCurrentUser();
}
_getCurrentUser=async()=>{
let user = await firebase.auth().currentUser;
console.log(user);
if (user != null) {
this.setState({
name: user.displayName,
email: user.email,
photoURL: user.photoURL
})
}
}
_updateProfile=()=>{
var user = firebase.auth().currentUser;
var credential;
user.updateProfile({
displayName: this.state.name,
photoURL: "https://randomuser.me/api/portraits/men/44.jpg",
}).then(function () {
Alert.alert('Success','Update Data successfull')
}).catch(function (error) {
Alert.alert('Error', 'Error happened')
});
// user.updateEmail(this.state.email).then( (user) => {
// user.reauthenticateAndRetrieveDataWithCredential(credential).then(function () {
// Alert.alert('Success', 'Update successfull')
// }).catch(function (error) {
// Alert.alert('Error', 'Error happened')
// });
// }).catch(function (error) {
// Alert.alert('Error', 'Error happened')
// });
}
_renderButtonOrSpinner=()=>{
if (this.state.loading) {
return <Spinner />;
}
return <Button onPress={this._updateProfile} title="Update" />;
}
static navigationOptions = {
title: 'Welcome to the app!',
};
render() {
return (
<KeyboardAvoidingView style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }} behavior="padding" enabled>
<Image source={{uri:this.state.photoURL}} style={{width:200,height:200}} />
<TextInput style={{ width: '90%',borderRadius: 5,borderColor: "grey" }} value={this.state.name} onChangeText={(text)=>{this.setState({name: text})}} placeholder="Name" />
<TextInput style={{ width: '90%',borderRadius: 5,borderColor: "grey" }} value={this.state.email} onChangeText={(text)=>{this.setState({email: text})}} placeholder="Email" />
{this._renderButtonOrSpinner()}
<Button title="Show me more of the app" onPress={this._showMoreApp} />
<Button title="Actually, sign me out :)" onPress={this._signOutAsync} />
</KeyboardAvoidingView>
);
}
_showMoreApp = () => {
this.props.navigation.navigate('Other');
};
_signOutAsync= () => {
firebase.auth().signOut().then(function () {
this.props.navigation.navigate('Auth');
}).catch(function (error) {
console.log(error)
});
};
}
@dwijonarko
Copy link
Author

kecuali App.js, file lain ada di direktori components

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment