React 로그인 Modal 만들기 8 - Redux 사용하기

React 로그인 Modal 만들기 8 - Redux 사용하기

모듈 설치하기

yarn add redux
yarn add react-redux

Action 정의

export const LOGIN_REQUEST = "login/LOGIN_REQUEST";

Action 생성 함수 및 Reducer 생성하기

import axios from 'axios';
import { LOGIN_REQUEST } from "../type"
const initialState = {
token: localStorage.getItem('token'),
};

export const loginRequest = (loginData) => {
const response = axios.post("/api/login", loginData)
.then((response) => {
localStorage.setItem("token", response.headers.authorization);
console.log(localStorage.getItem("token"));
return response.data;
})
.catch((err) => {
console.log(err);
});
return { type: LOGIN_REQUEST, data: response };
};

const LoginReducer = (state = initialState, action) => {
switch (action.type) {
case LOGIN_REQUEST:
return {
...state,
token: localStorage.getItem('token'),
};
default:
return state;
}
}

export default LoginReducer;

Store 생성하기

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import LoginReducer from './redux/reducers/LoginReducer'

const store = createStore(LoginReducer, composeWithDevTools())

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Dispatch 함수 적용

import axios from "axios";
import { useDispatch } from "react-redux";
import { loginRequest } from "../redux/reducers/LoginReducer";
import React, { useState, useCallback } from "react";
import {
LoginBody,
LoginFooter,
LoginHeader,
ModalBackGround,
ModalBox,
} from "../assets/css/login";

const LoginTemplate = ({ open, close }) => {
const [form, setForm] = useState({
email: "",
password: "",
});

const onChange = useCallback(
(e) => {
setForm({
...form,
[e.target.name]: e.target.value,
});
},
[form]
);

const dispatch = useDispatch();

const onClick = useCallback(() => {
dispatch(loginRequest(form));
});

return open ? (
<ModalBackGround>
<ModalBox>
<LoginHeader>
로그인
<button className="close" onClick={close}>
{" "}
&times;{" "}
</button>
</LoginHeader>
<LoginBody className="login-body">
<div>
<input
id="email"
name="email"
type="email"
placeholder="Email"
onChange={onChange}
/>
</div>
<div>
<input
id="password"
name="password"
type="password"
placeholder="Password"
onChange={onChange}
/>
</div>
</LoginBody>
<LoginFooter>
<button onClick={onClick}>로그인</button>
</LoginFooter>
</ModalBox>
</ModalBackGround>
) : null;
};

export default LoginTemplate;
Share