import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
import React from 'react';
import {getAuth,signOut,onAuthStateChanged} from 'firebase/auth';
import {getApps, initializeApp} from 'firebase/app';
import { initializeAuth, getReactNativePersistence,createUserWithEmailAndPassword,signInWithEmailAndPassword } from 'firebase/auth';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {useState} from 'react';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
if(getApps().length == 0){
const app = initializeApp(firebaseConfig);
initializeAuth(app,{
persistence: getReactNativePersistence(AsyncStorage)
});
}
const auth= getAuth();
function Form() {
const [email,setEmail] = useState("");
const [password,setPassword] = useState("");
const [user,setUser] = useState(null);
//onAuthStateChangedの記載
const createUser =() => {
setEmail(email);
setPassword(password);
createUserWithEmailAndPassword(auth,email,password);
onAuthStateChanged(auth,(user)=>{
setUser(auth.currentUser);
})
}
const logIn =() => {
setEmail(email);
setPassword(password);
signInWithEmailAndPassword(auth,email,password);
}
const logOut =() =>{
signOut(auth);
}
if(user){
return(
<View>
<Text>{user.email}でログイン中</Text>
<View style={{alignItems: 'center'}}>
<Button
title="ログアウト"
onPress={logOut}
/>
</View>
</View>
)
}else{
return(
<View>
<View>
<View>
<Text style={styles.header}>ユーザー登録</Text>
</View>
<View>
<Text>Email</Text>
<TextInput
style={styles.textInput}
onChangeText={email => setEmail(email)}
/>
</View>
<View>
<Text>Password</Text>
<TextInput
style={styles.textInput}
onChangeText={password => setPassword(password)}
/>
</View>
<View>
<Button title="Register"
onPress={createUser}
/>
</View>
</View>
</View>
)
}
}
export default function App() {
return (
<View style={styles.container}>
<Form/>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
header: {
fontSize:20
},
textInput: {
borderWidth: 1
}
});
EmailやPasswordには決まった制限があらかじめあるので作成するときに留意が必要。
今回は、Firebase 10.0.0を使用。
発展:パスワードを*****で表示したい場合どうすればよいでしょうか?