import React, { useState } from "react";
import { authService, firebaseInstance } from "../myBase";
const Auth = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [newAccount, setNewAccount] = useState(true);
const [error, setError] = useState("");
const onChange = (event) => {
const {
target: { name, value },
} = event;
if (name === "email") {
setEmail(value);
} else if (name === "password") {
setPassword(value);
}
};
const onSubmit = async (event) => {
event.preventDefault();
try {
let data;
if (newAccount) {
data = await authService.createUserWithEmailAndPassword(
email,
password
);
} else {
data = await authService.signInWithEmailAndPassword(email, password);
}
console.log(data);
} catch (error) {
setError(error.message);
}
};
const toggleAccount = () => setNewAccount((prev) => !prev);
const onSocialClick = async (event) => {
const {
target: { name },
} = event;
let provider;
if (name === "google") {
provider = new firebaseInstance.auth.GoogleAuthProvider();
} else if (name === "github") {
provider = new firebaseInstance.auth.GithubAuthProvider();
}
const data = await authService.signInWithPopup(provider);
console.log(data);
};
return (<div> <form onSubmit={onSubmit}> <input name="email" type="email" placeholder="Email" required value={email} onChange={onChange} /> <input name="password" type="password" placeholder="Password" required value={password} onChange={onChange} /> <input type="submit" value={newAccount ? "Create Account" : "Log In"} /> {error} </form> <span onClick={toggleAccount}> {newAccount ? "Log in" : "Create Account"} </span> <div> <button onClick={onSocialClick} name="google"> Continue with Google </button> <button onClick={onSocialClick} name="github"> Continue with github </button> </div> </div>
);
};
export default Auth;
로그인창 구성
useState, useEffect 를 이용하여 프로퍼티 관리
이메일과 비밀번호 인풋 박스를 만들고 계정을 만들기/ 로그인 구현
firebase 를 이용하여 로그인 환경을 backend 없이 구현 했다.
계정정보/ 계정생성 기능 구현 firebase.Stroage 를 통해 DB관리
firebase 내장 기능으로 깃과 구글 인증 로그인 기능 구현
try catch문으로 에러 발생시 경고
//삼항 연산자의 사용으로 효율적인 코드 작성