[새싹 프론트엔드] Firebase Authentication 1

Ryu·2022년 12월 29일
0

새싹

목록 보기
34/36

회원가입 구현

// SignUp.jsx
const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [name, setName] = useState('');
    const [admin, setAdmin] = useState('');
    const [errorMsg, setErrorMsg] = useState(' ');
    const [userObj, setUserObj] = useState(null);

    const auth = getAuth();
    
    const clickHandler = async (e) => {
        e.preventDefault();
        await createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                console.log(userCredential);
                setErrorMsg(' ');
                setEmail('');
                setPassword('');
                setName('');
                setAdmin('');
                // Signed in
                const user = userCredential.user;
                // ...
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                console.log(errorMessage);
                // ..
            });
    };

회원가입할 때 입력한 데이터 user의 uid를 이용해 firestore에 추가

// SignUp.jsx
setDoc(doc(db, 'users', user.uid), {
  username: name,
  userid: user.email,
  useradmin: admin,
});

로그인 구현 및 데이터 테스트

// SignIn.jsx
const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const userCollection = collection(db, 'users');

    const clickHandler = async (e) => {
        e.preventDefault();
        const auth = getAuth();
        await signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const dataPrint = async () => {
                    const user = userCredential.user;
                    const docRef = doc(userCollection, user.uid);
                    const data = await getDoc(docRef);
                    console.log(data.data());
                };
                dataPrint();
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                console.log(errorMessage);
            });
        setEmail('');
        setPassword('');
    };




새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 11주차 블로그 포스팅

0개의 댓글