23/11/23 til
2023. 11. 23. 00:57ㆍ카테고리 없음
파이어베이스를 이용한 회원가입 기능을 구현해보았다.
일단 작업중이고 완성하려면 멀었다.
firebase.js >>>
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app"; // 파이어베이스를 시작하기위한 초기값함수 임포트
import { getAuth } from "firebase/auth"; //솔직히 겟어쓰 어디서 쓰는지 모르겠슴
// TODO: Add SDKs for Firebase products that you want to use
// Your web app's Firebase configuration
const firebaseConfig = { // 파이어베이스에 가입후 프로젝트를만들고
apiKey: "AIzaSyCvuEPvbpa9UMcFd4ugcpLjovWQi0oSLis", // Authentication 을 시작하여 프로젝트 설정에서
authDomain: "react--team-project.firebaseapp.com", //가져온 파이어베이스 초기값설정
projectId: "react--team-project",
storageBucket: "react--team-project.appspot.com",
messagingSenderId: "449960898860",
appId: "1:449960898860:web:703e1416c2b78e4348fc89",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig); // 여기서 처음에 const app 앞에 export를 했는데
export const auth = getAuth(app); //오류가 떴다. initailizeApp을 찾을수 없다고
export default app; //익스포트 디폴트로 하니까 정상작동 튜터님의 도움으로 해결
MyPage.jsx
import {
createUserWithEmailAndPassword,
getAuth,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut,
} from "firebase/auth";
import React, { useEffect, useState } from "react";
import styled from "styled-components";
export default function Register() {
const [email, setEmail] = useState(""); // 회원가입시 요구되는 이메일과 패스워드
const [password, setPassword] = useState(""); //를 유즈스테이트화한다.
const auth = getAuth();
useEffect(() => {
onAuthStateChanged(auth, (user) => {
console.log("user", user);
});
}, []);
const onChange = (event) => {
const {
target: { name, value }, // 타겟 다음에 중괄호에 네임 벨류를 뒀는데
} = event; // 이거 구조분해할당인가?
if (name === "email") {
setEmail(value); //이프문은 이해했다. 이 온체인지 함수가
} //이메일에도 쓰이고 패스워드에서도 쓰이는데
//네임이 이메일일때랑 패스워드때일떄랑 if (name === "password") { //경우를 나눠서 셋 이메일이나 셋 패스워드를 하는듯
setPassword(value);
}
};
const signUp = async (event) => { // 어싱크 어웨이트 문은 아직 낯설지만
event.preventDefault(); //확실히 패치나 어쩌고 겟보다는 깔끔해 보인다.
try { //프리벤트 디폴트는 폼태그의 서브밋의 자동 리랜더링을 막음
const userCredential = await createUserWithEmailAndPassword(
auth, //이건 어쓰 에메일 패스워드를 인자로 갖는 함수같은데 이걸
email, //어떻게 하라는건지
password / /트라이 캐치문으로 응답을 제대로 받으면 트라이 안에것을실행
);
} catch (error) { //응답을 못받으면 캐치문 실행
console.error(error);
// const errorCode = error.code;
// const errorMessage = error.message;
}
};
const signIn = async (event) => {
event.preventDefault(); //역시 프리벤트 디폴트로 리랜더링막고
try {
const userCredential = await signInWithEmailAndPassword(
auth,
email,
password
);
} catch (error) {
console.error(error);
// const errorCode = error.code;
// const errorMessage = error.message;
}
};
const logOut = async (event) => {
event.preventDefault();
await signOut(auth); //로그아웃기능은 짧네 ㅋ
};
return (
<LoginWrapper>
<h2>로그인페이지</h2>
<form>
<div>
<label>이메일 : </label>
<input
type="email" //그동안 인풋에 벨류랑 온체인지는 자주 줬었는데
value={email} //타입하고 네임은 필요한건가?
name="email"
onChange={onChange}
required
/>
</div>
<div>
<label>비밀번호 : </label>
<input
type="password"
value={password}
name="password"
onChange={onChange}
required
/>
</div>
<button onClick={signUp}>회원가입</button>
<button onClick={signIn}>로그인</button>
<button onClick={logOut}>로그아웃</button>
</form>
</LoginWrapper>
);
}
const Div = styled.div` //스타일드 컴포넌트화
display: flex;
justify-content: center;
align-items: center;
height: 800px;
`
const LoginWrapper = styled.div` //회원가입 박스를 화면 정중앙에 오도록 css처리
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #fff1f0;
border: 1px solid black;
border-radius: 5px;
width: 400px;
height: 300px;
gap :20px;
& h2 {
font-size: 30px;
}
& button {
background-color: black;
color: white;
}
`
한게 없다 하하하하
회원가입해서 얻은 아이디하고 네임 받아야하는데 멘붕