내 로그인 정보 계속 불러오기

개발공부·2022년 12월 15일
0

* 결과 (로그인 유지, 새로고침 해도 유지됨)

  • 브라우저는 쿠키를 갖고 있으나 새로고침 할 때마다 서버 쪽으로 쿠키가 전달되지 않아 로그인이 풀린 것처럼 보임

loadMYINFO를 만들어서 로그인 한 경우를 계속 호출

server쪽

[routes/user.js]

router.get("/", async (req, res, next) => {
  // GET /user
  try {
    if (req.user) {
      const fullUserWithoutPassword = await User.findOne({
        where: { id: req.user.id },
        attributes: {
          exclude: ["password"],
        },
        include: [
          {
            model: Post,
            attributes: ["id"],
          },
          {
            model: User,
            as: "Followings",
            attributes: ["id"],
          },
          {
            model: User,
            as: "Followers",
            attributes: ["id"],
          },
        ],
      });
      res.status(200).json(fullUserWithoutPassword);
    } else {
      res.status(200).json(null);
    }
  } catch (error) {
    console.error(error);
    next(error);
  }
});

front쪽

[userSaga.js]

function loadMyInfoAPI() {
  return axios.get("/user");
}

function* loadMyInfo(action) {
  try {
    const data = action.payload;
    const result = yield call(loadMyInfoAPI, data);
    console.log("result", result);
    yield put(loadMyInfoSuccess(result.data));
  } catch (error) {
    yield put(loadMyInfoFailure(error));
    console.log(error);
  }
}

[pages/index.js]

  const dispatch = useDispatch();
  
  useEffect(() => {
    console.log("me", me);
    dispatch(loadMyInfoRequest());
  }, []); //두 번째 자리를 잊을 경우 무한 반복됨;

[userSlice.js] - redux-toolkit

 //내정보 불러오기 loadMyInfoRequest
    loadMyInfoRequest: (state) => {
      state.loadMyInfoLoading = true;
      state.loadMyInfoError = null;
      state.loadMyInfoComplete = false;
    },
    loadMyInfoSuccess: (state, action) => {
      state.loadMyInfoLoading = false;
      state.loadMyInfoComplete = true;
      state.me = action.payload;
    },
    loadMyInfoFailure: (state, action) => {
      state.loadMyInfoLoading = false;
      state.loadMyInfoError = action.error;
    },
profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글