LoginSaga
import axios from "axios";
import { resolveSoa } from "dns";
import { NextRouter } from "next/router";
import {
call,
getContext,
put,
takeEvery,
takeLatest,
} from "redux-saga/effects";
import { LOGIN_PENDING, LOGIN_SUCCESS } from "../actions/actionTypes";
import { LoginData, LoginJson } from "../types/state";
const checkdata = async () => {
const res = await axios.get(
);
return res.data;
};
여기서 데이터를 받아와서 반환하도록 설계했습니다.
function* checklogin({
type,
payload,
router,
}: {
type: String;
payload: LoginData;
router: NextRouter;
}) {
try {
const data: LoginJson = yield call(checkdata);
const result: LoginData | undefined = data.login.find((res: LoginData) => {
if (payload.id == res.id && payload.password == res.password) {
return res;
}
});
if (result) {
yield put({ type: LOGIN_SUCCESS, payload, router });
const history = getContext("history");
} else {
alert("아이디와 비밀번호 확인해주세요");
}
} catch (e) {
console.log(e);
}
}
전달받은 type payload router를 전달 받아주고 call로 api데이터를 받아와줍니다.
result로 payload에서 받아오 로그인 데이터가 맞는지 확인해주고
if문으로 데이터가 맞다면 LOGIN_SUCCESS를 실행시켜서 로그인처리해주게 됩니다.
export default function* watchLogin() {
yield takeLatest(LOGIN_PENDING, checklogin);
}
이부분에서 LOGINPENDING이 실행되면 checklogin이 실행되도록 설정합니다.
Sagas/index
import { all, call } from "redux-saga/effects";
import watchLogin from "../LoginSaga";
export default function* rootSaga() {
yield all([call(watchLogin)]);
}
여기서 위의 watchLogin을 작동할수있또록 all과 call을 사용해줍니다.'next+ts' 카테고리의 다른 글
next+ts Redux index 전체 코드 둘러보기(마지막) (0) | 2022.05.12 |
---|---|
next+ts Redux reducer(SAGA제외) 전체 코드 둘러보기 (0) | 2022.05.09 |
next+ts Redux action 전체 코드 둘러보기 (0) | 2022.05.08 |
next+ts 마이페이지 전체 코드 둘러보기(Component+container) (0) | 2022.05.07 |
next+ts 로그인 페이지 전체 코드 둘러보기(Component+container) (0) | 2022.05.04 |