본문 바로가기
[Study] 개발 공부

[React+Vite/TS] Firebase 사용하여 이메일/비밀번호로 계정 생성하기

by 지공A 2024. 5. 14.
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      setLoading(true);
      // 계정 생성
      if (isLoading || name === "" || email === "" || password === "") return;
      // 계성 생성 성공 시 자격증명
      const credentials = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      );
      console.log(credentials.user);
      // 사용자 이름 set
      await updateProfile(credentials.user, {
        displayName: name,
      });
      // 홈페이지로 redirect
      navigate("/");
    } catch (e) {
      // 에러 핸들링
    } finally {
      setLoading(false);
    }

    // console.log(name, email, password);
  };


1. 로딩 상태가 아니며, 이름/이메일/비밀번호가 빈 string이 아닐 경우 계정을 생성

 

2. createUserWithEmailAndPassword(auth, email, password)

(alias) createUserWithEmailAndPassword(auth: Auth, email: string, password: string): Promise<UserCredential>
import createUserWithEmailAndPassword

Creates a new user account associated with the specified email address and password.

@remarks
On successful creation of the user account, this user will also be signed in to your application.

  •  계정 생성 성공 시 자격 증명 생성
  •  성공적으로 계정이 생서되면, 로그인 상태가 된다

3. 그러면 이름(name)은 어디에? updateProfile(user, { displayName, photoURL? }) 에서 갱신해준다.

 

4. 성공 시 홈페이지로 redirect, 이후 Loading state를 false로 변경해준다.