재밌고 어려운 IT를 이해해보자~!

login with react 본문

React, Node Js

login with react

언제나즐거운IT 2024. 6. 3. 22:59

loginPage.js

import React, { useState } from 'react';
import Axios from 'axios'
import {useDispatch} from 'react-redux';

function LoginPage() {
    const dispatch = useDispatch();

    const [Email, setEmail] = useState("");
    const [Password, setPassword] = useState("");

    const onEmailHandler = (event) => {
        setEmail(event.currentTarget.value);
    }

    const onPasswordHandler = (event) => {
        setPassword(event.currentTarget.value);
    }

    const onSubmitHandler = (event) => {
        //페이지 새로고침을 막기위함 
        event.preventDefault();


        // 폼 제출 시 수행할 동작
        console.log('Email:', Email);
        console.log('Password:', Password);

        let body = {
            email: Email,
            password: Password
        }
        dispatch(loginUser(body))
        .then(response => {
            if(response.payload.loginSuccess) {
                props.history.push('/')
            }
        })

    }

    return (
        <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100%', height: '100vh'
        }}>
            <form style={{ display: 'flex', flexDirection: 'column' }} onSubmit={onSubmitHandler}>
                <label>Email</label>
                <input type="email" value={Email} onChange={onEmailHandler} />
                <label>Password</label>
                <input type="password" value={Password} onChange={onPasswordHandler} />
                <br />
                <button type="submit">Login</button>
            </form>
        </div>
    );
}

export default LoginPage;

 

types. js

export const LOGIN_USER = "login_user";

 

user_action.js

import axios from 'axios';
import {
    LOGIN_USER
} from './types';

export function loginUser(dataToSubmit) {
    const request = Axios.post('/api/users/login', dataToSubmit)
    .then(response => { response.data })

    return {
        type: "LOGIN_USER",
        payload: request
    }
}

 

index.js

import { combineReducesrs } from 'redux';
 import user from './user.reducer';

const rootReducer = combineReducers({
     user
})

export default rootReducer;

 

user_reducer.js

import {
    LOGIN_USER
} from '../_actions/types';

export default function (state = {}, action) {
    switch (action.type) {
        case LOGIN_USER:
            return {...state, loginSuccess: action.payload }
        break;

        default:
           return state;
    }
}

 

전체 프로세스

  1. 사용자가 이메일과 비밀번호를 입력하고 로그인 버튼을 클릭
  2. onSubmitHandler 함수가 호출되어 로그인 정보를 포함한 loginUser 액션을 디스패치
  3. loginUser 액션은 서버에 로그인 요청을 보내고, 응답 데이터를 LOGIN_USER 타입의 액션으로 반환
  4. 리듀서가 이 액션을 처리하여 loginSuccess 상태를 업데이트
  5. loginSuccess가 true이면, 사용자를 홈 페이지로 리디렉션
 
 

'React, Node Js' 카테고리의 다른 글

LoginPage with React -1  (0) 2024.05.24
React Hook  (0) 2024.05.23
Middleware, Redux thunk, promise  (2) 2024.05.21
Ant Design, Redux  (0) 2024.05.16
Concurrently  (0) 2024.05.15
Comments