728x90
1. 회원가입 구현하기
더보기
👉 [순서대로 하나씩 해봅시다!]
이 부분은 함께 코딩하는 것보다, 일단 어떻게 쓰는 지 순서를 아는 게 중요합니다.
아래 코드스니펫을 준비해두었으니 쭉 눈으로 따라해보시고, 복습 할 때는 순서만 보고 코드를 짜보세요. 😉
적용 순서
- firebase.js에 만들어둔 auth 가져오기
- 리덕스에서 signupFB 함수 만들기
- auth.createUserWithEmailAndPassword()로 가입 시키기
- Signup 컴포넌트에서 signupFB를 호출!
- 가입한 후, display_name 바로 업데이트하기
- 사용자 정보 업데이트 후에 메인 페이지로 이동하기
src/redux/modules/user.js
// user.js
import { createAction, handleActions } from "redux-actions";
// 액션이랑 리듀서를 쉽게 만들어 주는 패키지
import { produce } from "immer";
import { setCookie, getCookie, deleteCookie } from "../../shared/Cookie";
import { auth } from "../../shared/firebase";
import { FirebaseError } from "@firebase/util";
// actions
// const LOG_IN = "LOG_IN";
const LOG_OUT = "LOG_OUT";
const GET_USER = "GET_USER";
const SET_USER = "SET_USER";
// action creators
// const logIn = createAction(LOG_IN, (user) => ({ user }));
const logOut = createAction(LOG_OUT, (user) => ({ user }));
const getUser = createAction(GET_USER, (user) => ({ user }));
const setUser = createAction(SET_USER, (user) => ({ user }));
// initialState
const initialState = {
user: null,
is_login: false,
};
// middleware actions
const logInAction = (user) => {
return function (dispatch, getState, { history }) {
console.log(history);
dispatch(setUser(user));
history.push("/");
};
};
const signUpFB = (id, pwd, user_name) => {
return function (dispatch, getState, { history }) {
auth
.createUserWithEmailAndPassword(id, pwd)
.then((user) => {
auth.currentUser.updateProfile({
displayName : user_name,
}).then(()=>{
dispatch(setUser({user_name : user_name, id : id, user_profile : ''}));
history.push('/');
}).catch((error)=>{
console.log(error)
})
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage)
});
};
};
// reducer
export default handleActions(
{
[SET_USER]: (state, action) =>
produce(state, (drapt) => {
setCookie("is_login", "success");
drapt.user = action.payload.user;
drapt.is_login = true;
}),
[LOG_OUT]: (state, action) =>
produce(state, (drapt) => {
deleteCookie("is_login");
drapt.user = null;
drapt.is_login = false;
}),
[GET_USER]: (state, action) => produce(state, (drapt) => {}),
},
initialState
);
// action creator export
const actionCreators = {
// logIn,
logOut,
getUser,
logInAction,
setUser,
signUpFB,
};
export { actionCreators };
src/pages/Signup.js
import React from "react";
import { Grid, Text, Input, Button } from "../elements";
import { useDispatch } from "react-redux";
import { actionCreators as userActions } from "../redux/modules/user";
const Signup = (props) => {
const dispatch = useDispatch();
const [id, setId] = React.useState();
const [pwd, setPwd] = React.useState();
const [pwdCheck, setPwdCheck] = React.useState();
const [user_name, setUserName] = React.useState();
const signUp = () => {
if(pwd !== pwdCheck){
return;
}else if(id === '' || pwd === '' || user_name === ''){
return;
}
dispatch(userActions.signUpFB(id, pwd, user_name));
};
return (
<React.Fragment>
<Grid padding="16px">
<Text size="32px" bold>
회원가입
</Text>
<Grid padding="16px 0px">
<Input
label="아이디"
placeholder="아이디를 입력해주세요."
_onChange={(e) => {
setId(e.target.value);
}}
/>
</Grid>
<Grid padding="16px 0px">
<Input
label="닉네임"
placeholder="닉네임을 입력해주세요."
_onChange={(e) => {
setUserName(e.target.value);
}}
/>
</Grid>
<Grid padding="16px 0px">
<Input
label="비밀번호"
placeholder="비밀번호를 입력해주세요."
_onChange={(e) => {
setPwd(e.target.value);
}}
/>
</Grid>
<Grid padding="16px 0px">
<Input
label="비밀번호 확인"
placeholder="비밀번호를 다시 입력해주세요."
_onChange={(e) => {
setPwdCheck(e.target.value);
}}
/>
</Grid>
<Button text="회원가입하기" _onClick={signUp}></Button>
</Grid>
</React.Fragment>
);
};
Signup.defaultProps = {};
export default Signup;
2. 로그인 구현하기
더보기
👉 [순서대로 하나씩 해봅시다!]
이 부분은 함께 코딩하는 것보다, 일단 어떻게 쓰는 지 순서를 아는 게 중요합니다.
아래 코드스니펫을 준비해두었으니 쭉 눈으로 따라해보시고, 복습할 때는 순서만 보고 코드를 짜보세요. 😉
적용 순서
- firebase.js에 만들어둔 auth 가져오기
- 리덕스에서 loginFB 함수 만들기
- auth.signInWithEmailAndPassword()로 로그인
- Login 컴포넌트에서 loginFB를 호출!
- 리덕스의 user 정보 업데이트 후에 메인 페이지로 이동하기
src/redux/modules/user.js
// user.js
import { createAction, handleActions } from "redux-actions";
// 액션이랑 리듀서를 쉽게 만들어 주는 패키지
import { produce } from "immer";
import { setCookie, getCookie, deleteCookie } from "../../shared/Cookie";
import { auth } from "../../shared/firebase";
// actions
// const LOG_IN = "LOG_IN";
const LOG_OUT = "LOG_OUT";
const GET_USER = "GET_USER";
const SET_USER = "SET_USER";
// action creators
// const logIn = createAction(LOG_IN, (user) => ({ user }));
const logOut = createAction(LOG_OUT, (user) => ({ user }));
const getUser = createAction(GET_USER, (user) => ({ user }));
const setUser = createAction(SET_USER, (user) => ({ user }));
// initialState
const initialState = {
user: null,
is_login: false,
};
// middleware actions
const loginFB = (id, pwd) => {
return function (dispatch, getState, { history }) {
auth
.signInWithEmailAndPassword(id, pwd)
.then((user) => {
// 로그인 후 작업
dispatch(
setUser({ user_name: user.displayName, id: id, user_profile: "" }
))
history.push('/')
})
.catch((error) => {
console.log(error)
});
};
};
const signUpFB = (id, pwd, user_name) => {
return function (dispatch, getState, { history }) {
auth
.createUserWithEmailAndPassword(id, pwd)
.then((user) => {
auth.currentUser
.updateProfile({
displayName: user_name,
})
.then(() => {
// 회원가입 후 작업
dispatch(
setUser({ user_name: user_name, id: id, user_profile: "" })
);
history.push("/");
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
});
};
};
// reducer
export default handleActions(
{
[SET_USER]: (state, action) =>
produce(state, (drapt) => {
setCookie("is_login", "success");
drapt.user = action.payload.user;
drapt.is_login = true;
}),
[LOG_OUT]: (state, action) =>
produce(state, (drapt) => {
deleteCookie("is_login");
drapt.user = null;
drapt.is_login = false;
}),
[GET_USER]: (state, action) => produce(state, (drapt) => {}),
},
initialState
);
// action creator export
const actionCreators = {
// logIn,
logOut,
getUser,
signUpFB,
loginFB,
};
export { actionCreators };
src/pages/Login.js
import React from "react";
import { getCookie, setCookie, deleteCookie } from "../shared/Cookie";
import { Text, Input, Grid, Button } from "../elements";
import { useDispatch } from "react-redux";
import {actionCreators as userActions} from '../redux/modules/user'
const Login = (props) => {
const dispatch = useDispatch();
const [id, setId] = React.useState();
const [pwd, setPwd] = React.useState();
const login = () => {
if(id === '' || pwd === ''){
window.alert("아이디 혹은 비밀번호가 공란입니다. 입력 해주세요");
return;
}
dispatch(userActions.loginFB(id , pwd));
};
return (
<React.Fragment>
<Grid padding="16px">
<Text size="32px" bold>
로그인
</Text>
<Grid padding="16px 0px">
<Input
label="아이디"
placeholder="아이디를 입력해주세요."
_onChange={(e) => {
setId(e.target.value)
}}
/>
</Grid>
<Grid padding="16px 0px">
<Input
label="패스워드"
type="password"
placeholder="패스워드 입력해주세요."
_onChange={(e) => {
setPwd(e.target.value)
}}
/>
</Grid>
<Button
text="로그인하기"
_onClick={login}
></Button>
</Grid>
</React.Fragment>
);
};
export default Login;
src/elements/input.js
import React from "react";
import styled from "styled-components";
import {Text, Grid} from "./index";
const Input = (props) => {
const {label, placeholder, _onChange, type} = props;
return (
<React.Fragment>
<Grid>
<Text margin="0px">{label}</Text>
<ElInput type={type} placeholder={placeholder} onChange={_onChange} />
</Grid>
</React.Fragment>
);
}
Input.defaultProps = {
label: '텍스트',
type : "text",
placeholder: '텍스트를 입력해주세요.',
_onChange: () => {}
}
const ElInput = styled.input`
border: 1px solid #212121;
width: 100%;
padding: 12px 4px;
box-sizing: border-box;
`;
export default Input;
src/shared/Firebase.js
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
// 인증정보!
};
firebase.initializeApp(firebaseConfig);
const apiKey = firebaseConfig.apiKey;
const auth = firebase.auth();
export{auth, apiKey};
728x90
댓글