Firebase signup 사용하기
firebase에 Authenication
이메일/비밀번호를 누르고
체크 후 저장
코드 만들기
회원가입
lib/firebase.prod.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const config = {
apiKey: process.env.REACT_APP_apiKey,
authDomain: process.env.REACT_APP_authDomain,
projectId: process.env.REACT_APP_projectId ,
storageBucket: process.env.REACT_APP_storageBucket ,
messagingSenderId: process.env.REACT_APP_messagingSenderId ,
appId: process.env.REACT_APP_appId,
measurementId: process.env.REACT_APP_measurementId
};
const firebase = initializeApp(config);
const auth = getAuth();
export { firebase, auth };
page/signup.js
import React, { useState, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { FirebaseContext } from '../context/firebase';
import { createUserWithEmailAndPassword, updateProfile } from 'firebase/auth';
import { Form } from '../components';
import { HeaderContainer } from '../containers/header';
import { FooterContainer } from '../containers/footer';
import * as ROUTES from '../constants/routes';
export default function SignUp() {
const navigate = useNavigate();
const { auth } = useContext(FirebaseContext);
const [firstName, setFirstName] = useState('');
const [emailAddress, setEmailAddress] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const isInvalid = firstName === '' || password === '' || emailAddress === '';
const handleSignup = (event) => {
event.preventDefault();
return createUserWithEmailAndPassword(auth, emailAddress, password)
.then((result) =>
updateProfile(result.user, {
displayName: firstName,
photoURL: Math.floor(Math.random() * 5) + 1,
}).then(() => {
navigate.push(ROUTES.BROWSE);
})
)
.catch((error) => {
setFirstName('');
setEmailAddress('');
setPassword('');
setError(error.message);
});
};
return (
<>
<HeaderContainer>
<Form>
<Form.Title>Sign Up</Form.Title>
{error && <Form.Error>{error}</Form.Error>}
<Form.Base onSubmit={handleSignup} method="POST">
<Form.Input
placeholder="First name"
value={firstName}
onChange={({ target }) => setFirstName(target.value)}
/>
<Form.Input
placeholder="Email address"
value={emailAddress}
onChange={({ target }) => setEmailAddress(target.value)}
/>
<Form.Input
type="password"
value={password}
autoComplete="off"
placeholder="Password"
onChange={({ target }) => setPassword(target.value)}
/>
<Form.Submit disabled={isInvalid} type="submit" data-testid="sign-up">
Sign Up
</Form.Submit>
</Form.Base>
<Form.Text>
Already a user? <Form.Link to="/signin">Sign in now.</Form.Link>
</Form.Text>
<Form.TextSmall>
This page is protected by Google reCAPTCHA to ensure you're not a bot. Learn more.
</Form.TextSmall>
</Form>
</HeaderContainer>
<FooterContainer />
</>
);
}
context/firebase.js
import { createContext } from 'react';
export const FirebaseContext = createContext(null);
index.js
import React from 'react';
import App from './app';
import 'normalize.css';
import { createRoot } from 'react-dom/client';
import { GlobalStyles } from './global-styles';
import { firebase,auth } from './lib/firebase.prod';
import { FirebaseContext } from './context/firebase';
const rootElement = document.getElementById('root');
createRoot(rootElement).render(
<>
<FirebaseContext.Provider value={{ firebase,auth }}>
<GlobalStyles />
<App />
</FirebaseContext.Provider>
</>
);
index.js에서 firebase.prod 를 받아오고
page인 signup.js에서 사용할 때는 context/firebase.js 를 통해 받아온다.
테스트 확인
트러블 슈팅
튜토리얼을 따라가다보면
ERROR in ./src/pages/signin.js 16:18-28
export 'useHistory' (imported as 'useHistory')
이런 오류가 난다.
React Router v6에서는 useHistory hook이 더 이상 사용되지 않습니다. 대신 useNavigate hook을 사용해야 합니다.
또한 signup 함수는
const handleSignup = (event) => {
event.preventDefault();
return firebase
.auth()
.createUserWithEmailAndPassword(emailAddress, password)
.then((result) =>
result.user
.updateProfile({
displayName: firstName,
photoURL: Math.floor(Math.random() * 5) + 1,
})
.then(() => {
history.push(ROUTES.BROWSE);
})
)
.catch((error) => {
setFirstName('');
setEmailAddress('');
setPassword('');
setError(error.message);
});
};
이런식으로 구성이 되었는데
현재 버전 firebase에는 호환이 되지 않는코드이므로
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
를 사용해서 구성을 해야 했다.
'Dev > React 넷플릭스클론' 카테고리의 다른 글
넷플릭스 클론코딩 11 라우팅 페이지 (0) | 2023.09.07 |
---|---|
넷플릭스 클론코딩 10 로그인 기능구현 (0) | 2023.09.07 |
넷플릭스 클론코딩 8 firebase 설정 (0) | 2023.09.06 |
넷플릭스 클론코딩 7 메인페이지, Route 설정 (0) | 2023.09.06 |
넷플릭스 클론코딩 6 global-style, eslint (0) | 2023.09.06 |