現役調理師がエンジニアを目指します!4-3(FIREBASE認証、登録)
FIREBASEでログイン、登録機能の実装
今回はReact Firebase Hooksの• Authentication Hooks使用して作成します
npm i react-firebase-hooks
React Firebase Hooks ⇒
/auth ⇒
README.md ⇒
useCreateUserWithEmailAndPasswordを使用
今回大事な部分
//FIREBASE LOGIC
const [
createUserWithEmailAndPassword,
user,
loading,
userError,
] = useCreateUserWithEmailAndPassword(auth);
このカスタムフックを使用することで、メールとパスワードによる登録を簡単に行えるよう
const SignUp = () => {
const setModalState = useSetRecoilState(authModalState);
const [ signUp , setSignUp ] = useState({
email : "",
password : "",
confirmPassword : "",
})
const [ error , setError] = useState("");
//FIREBASE LOGIC
const [
createUserWithEmailAndPassword,
user,
loading,
userError,
] = useCreateUserWithEmailAndPassword(auth);
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if ( error ) setError("")
if ( signUp.password !== signUp.confirmPassword) {
setError("パスワードが違います")
return;
}
createUserWithEmailAndPassword( signUp.email, signUp.password );
};
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSignUp((prev) => ({
...prev,
[event.target.name]: event.target.value,
}));
};
return (
<form onSubmit={onSubmit}>
<Input
required
name='email'
placeholder='メールアドレス'
type='email'
mb={2}
onChange={onChange}
fontSize="10pt"
_placeholder={{ color: 'gray.500'}}
_hover={{ bg: 'white', border: '1px solid', borderColor: 'orange.500'}}
_focus={{ bg: 'white', border: '1px solid', borderColor: 'orange.500' }} bg='gray.50'/>
<Input
required
name='password'
placeholder='パスワード'
type='password'
mb={2}
onChange={onChange}
fontSize='10pt'
_placeholder={{ color: 'gray.500'}}
_hover={{ bg: 'white', border: '1px solid', borderColor: 'orange.500'}}
_focus={{ bg: 'white', border: '1px solid', borderColor: 'orange.500' }} bg='gray.50'/>
<Input
required name='password'
placeholder='パスワードを再入力'
type='password'
mb={2}
onChange={onChange}
fontSize='10pt'
_placeholder={{ color: 'gray.500'}}
_hover={{ bg: 'white', border: '1px solid', borderColor: 'orange.500'}}
_focus={{ bg: 'white', border: '1px solid', borderColor: 'orange.500' }} bg='gray.50'/>
{error &&
<Text textAlign='center' fontSize='10pt' color='red'>
{error}
</Text>
}
<Button width="100%" height="30px" mb={4} mt={4} type='submit' isLoading={loading}>会員登録</Button>
<Flex justify='center' align='center' mb={4}>
<Text fontSize='9pt' mr={2}>登録はお済みですか? |</Text>
<Text
cursor='pointer'
fontSize='9pt'
fontWeight={700}
color='orange.500'
mr={2}
onClick={() => setModalState((prev) => ({ ...prev, view: "ログイン"}))}>ログインはこちらから</Text>
</Flex>
</form>
)
}
export default SignUp
onSubmit関数で
createUserWithEmailAndPasswordに引数(メールアドレス, パスワード)を渡しForm内のものをFIREBASEに送信する。
*event.preventDefault() ⇒ submit(送信)された時のページの更新を防ぐ
FIREBASEのコンソールに移動
1.Authenticationを開き、sign-in methodに移動
2.ログインプロバイダの追加(今回はGoogle認証とメール&パスワード認証を選択)
*使いたいプロバイダを選択しないと一生反映されないので注意
3.実際に先ほど作った機能を使って登録を行い、usersに移動して登録したものが反映されていたら成功