본문 바로가기

트위터(React, TypeScript, Firebase, Vite)

08. Authentication - Create Account

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

create-accrount.tsx

import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { useState } from "react";
import { styled } from "styled-components";
import { auth } from "./firebase";
import { useNavigate } from "react-router-dom";

const Wrapper = styled.div`
  height: 100vh;                          /* 화면 전체 높이를 기준으로 중앙 정렬 */ 
  display: flex;
  justify-content: center;                /* 수평 중앙 */
  align-items: center;                    /* 수직 중앙 */
  flex-direction: column;
  width: 420px;
  margin: 0 auto;                         /* 화면 가운데로 */
  padding: 50px 0px;

`;

const Title = styled.h1`
  font-size: 42px;
`;

const Form = styled.form`
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
`;

const Input = styled.input`
  padding: 10px 20px;
  border-radius: 50px;
  border: none;
  width: 100%;
  font-size: 16px;
  &[type="submit"] {
    cursor: pointer;
    &:hover {
      opacity: 0.8;
    }
  }
`;

const Error = styled.span`
  font-weight: 600;
  color: tomato;
`;

export default function CreateAccount() {
  const navigate = useNavigate();
  const [isLoading, setLoading] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const {
      target: { name, value },
    } = e;
    if (name === "name") {
      setName(value);
    } else if (name === "email") {
      setEmail(value);
    } else if (name === "password") {
      setPassword(value);
    }
  };
  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if(isLoading === true ||name === "" || email === "" || password === ""){
      return;
    }
    try {
      setLoading(true);
      const credentials = await createUserWithEmailAndPassword(auth, email, password)
                                                              // createUserWithEmailAndPassword는 Firebase Auth SDK에서 제공하는 함수로 인자에 auth 인스턴스가 필요하다.
                                                              // firebase.ts 파일 내 auth 인스턴스가 생성되어 있음!
      await updateProfile(credentials.user, {displayName : name});  
      navigate("/");                                                            
    } catch (e) {
     
    } finally {
      setLoading(false);
    }
  };
  return (
    <Wrapper>
      <Title>Join 𝕏</Title>
      <Form onSubmit={onSubmit}>
        <Input
          onChange={onChange}
          name="name"
          value={name}
          placeholder="Name"
          type="text"
          required
        />
        <Input
          onChange={onChange}
          name="email"
          value={email}
          placeholder="Email"
          type="email"
          required
        />
        <Input
          onChange={onChange}
          value={password}
          name="password"
          placeholder="Password"
          type="password"
          required
        />
        <Input
          type="submit"
          value={isLoading ? "Loading..." : "Create Account"}
        />
      </Form>
      {error !== "" ? <Error>{error}</Error> : null}
    </Wrapper>
  );
}

firebase.ts

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

import {getAuth} from "firebase/auth";

/* 
  도메인, api ket 등 여러가지 키 값들이 포함된 config 개체를 
  firebase app 생성 시에 firebaseConfig 객체가 주어졌다.
*/
const firebaseConfig = {
  apiKey: "AIzaSyDRHBD9TNQFRsFTV8nf8N2SRJ7C65c4r08",
  authDomain: "nwitter-reloaded-68b8c.firebaseapp.com",
  projectId: "nwitter-reloaded-68b8c",
  storageBucket: "nwitter-reloaded-68b8c.firebasestorage.app",
  messagingSenderId: "464085535303",
  appId: "1:464085535303:web:ba1b5d7558448f3dc07f62",
  measurementId: "G-HF9RX7ZX6F"
};

/*
  firebaseConfig 옵션을 통해서 app을 생성한다.
*/
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

/*
  app에 대한 인증 서비스를 사용한다.
*/
export const auth = getAuth(app)






nwitter-reloaded.z01
19.53MB
nwitter-reloaded.z02
19.53MB
nwitter-reloaded.z03
19.53MB
nwitter-reloaded.z04
19.53MB
nwitter-reloaded.z05
19.53MB
nwitter-reloaded.zip
14.58MB

 

'트위터(React, TypeScript, Firebase, Vite)' 카테고리의 다른 글

10. Authentication - Log In  (0) 2025.04.15
09. Authentication - Protected Routes  (0) 2025.04.15
07. Authetication - Forms and UI  (0) 2025.04.14
06. Authentication - Setup  (0) 2025.04.11
04. Firebase Project  (0) 2025.04.11