React : 로그인, 로그아웃

김가영·2020년 11월 24일
4

Web

목록 보기
4/11
post-thumbnail

Inflearn : 따라하며 배우는 노드 리액트 기본

concurrently

백앤드와 react 함께 구동하기
back-end 서버에 concurrently 추가 후

  • package.json
"scripts": {
    "start": "node server/index.js",
    "backend": "nodemon server/index.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "concurrently \"npm run backend\" \"npm run start --prefix client\""
  },

npm run dev를 통해 백앤드와 리액트 함꼐 구동 가능

Reducer

  • a function describing how the application's state changes
    (previousState, action) => nextState

Redux-devtools

$ npm install redux-devtools-extension

  • src/index.js
import {composeWithDevTools} from 'redux-devtools-extension';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore, composeWithDevTools());

로그인 페이지

  • src/components/views/LoginPage/LoginPage.js
import Axios from 'axios';
import React, {useState} from 'react'
import { useDispatch } from 'react-redux'
import { loginUser} from '../../../_actions/user_action';

function LoginPage(props) {

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

    //typing 하면 onChange 를 발생시켜 state를 바꿔주어 value를 바꾼다.
    const onEmailHandler = (event) => {
        setEmail(event.currentTarget.value);
    }
    const onPasswordHandler = (event) => {
        setPassword(event.currentTarget.value);
    }
    const onSubmitHandler = (event) => {
        // page refresh를 막아준다
        event.preventDefault();

        // 서버에 보내기
        let body = {
            email : Email,
            password : Password
        }

        dispatch(loginUser(body))
      		// 로그인되면 /(index페이지)로 이동
            .then(response => {
                if (response.payload.loginSuccess) {
                    props.history.push('/')
                } else {
                    alert('Error')
                }
            })

        // Axios.post('/api/users/login', body)
        // .then(response => {
            
        // })
    }

    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

페이지 만들어주기

action → reducer → store → (subscribe) → react component → (action) → action

  • src/_actions/user_action.js
import axios from 'axios';
import{
    LOGIN_USER
} from './types';

export function loginUser(dataTosubmit) {
    // 서버에서 받은 data를 request에 저장
    const request = axios.post('/api/users/login', dataTosubmit)
        .then(response => 
            response.data);
    return {
        type: "LOGIN_USER",
        payload: request
    }
}
  • src/_actions/types.js
export const LOGIN_USER = "login_user";
//export const REGISTER_USER = 'register_user';
  • src/_reducers/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;
            break;
    }
}
  • src/_reducers/index.js
import {combineReducers } from 'redux';
import user from './user_reducer';

const rootReducer = combineReducers({
    user,
})

export default rootReducer;

로그아웃

not using redux

  • LandingPage.js
import React, {useEffect} from 'react'
import axios from 'axios';

function LandingPage(props) {
    
    useEffect(() => {
        axios.get('/api/hello')
        .then(response => console.log(response.data))
    }, [])

    const onClickHandler = () => {
        axios.get('/api/users/logout')
        .then(response => {
            if (response.data.success) {
                props.history.push('/login');
            } else {
                alert('로그아웃에 실패');
            }
            
        })
    }
    return (
        <div style ={{
            display : 'flex', justifyContent : 'center', alignItems: 'center',
            width : '100%', height : '100vh'
        }}>
            <h2>시작 페이지</h2>

            <button onClick = {onClickHandler}>로그아웃</button>
        </div>
    )
}

export default LandingPage
profile
개발블로그

0개의 댓글