next+ts
next+ts Redux reducer SAGA전체 코드 둘러보기
멈추지않아
2022. 5. 11. 17:07
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을 사용해줍니다.