리덕스로 회원가입 구현하기

Yeongsan Son·2021년 5월 26일
0
  • RegisterPage.js
import React, {useState} from 'react';
import {useDispatch} from 'react-redux';
import {registerUser} from './user_action'

const RegisterPage = (props) => {
  const dispatch = useDispatch();
  
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useStatae('');
  const [confirmPassword, setConfirmPassword] = useState('');
  
  const onChangeName = (e) => {
    setUsername(e.target.value);
  }
  const onChangeEmail = (e) => {
    setEmail(e.target.value);
  }
  const onChangePassword = (e) => {
    setPassword(e.target.value);
  }
  const onChangeConfirmPassword = (e) => {
    setConfirmPassword(e.target.value);
  }
  
  const handleSubmit = (e) => {
  	e.preventDefault();
    
    if(password !== ConfirmPassword){
      return alert('입력한 비밀번호가 다릅니다!');
    }
    
    let body = {
      username,
      email,
      password
    }
    dispatch(registerUser(body)
      .then(res => {
      	if(res.payload.success) {
          props.history.push('/login'); // 로그인 페이지로 리다이렉션
        } else {
          alert('회원가입에 실패했습니다.');
        }     
      })
  }
  
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>Name</label>
        <input type="text" value={username} onChange={onChangeNmae}/>
        <label>Email</label>
        <input type="email" value={email} onChange={onChangeEmail}/>
        <label>Password</label>
        <input type="password" value={password} onChange={onChangePassword}/>
        <label>Confirm Password</label>
        <input type="password" value={confirmPassword} onChange={onChangeConfirmPassword}/>
        <br />
        <button type="submit">Register</buttton>
      </form>
    </div>
  );
}
  • user_action.js
import axios from 'axios';
import {RGISTER_USER} from './types';

export function registerUser(dataToSubmit) {
  const request = axios.post('/api/users/register', dataToSubmit).then(response => response.data)
  
  return {
    type: REGISTER_USER,
    payload: request
  }
}
  • types.js
export const REGISTER_USER = "REGISTER_USER";
  • user_reducers.js
import {REGISTER_USER} from 'types';

export default function (state={}, action) {
  switch(action.type) {
    case REGISTER_USER:
      return {...state, register: action.payload} 
      break;
    default: 
      return state; 
  }
}
profile
매몰되지 않는 개발자가 되자

0개의 댓글