[DAY43] Login, cookie

1nxeo·2023년 3월 20일

항해99

목록 보기
40/63
post-thumbnail
  1. 문제
    로그인 완료 후에 '/'로 자동으로 넘어가지 않는다..

  2. 시도

  • 로그인 버튼을 눌렀을 때 실행되는 함수에 navigate로 페이지를 이동하게 해줌. 이 때 async, await로 비동기 처리를 해주기.
const submitLoginHandler = async (e) => {
    e.preventDefault();
    await dispatch(__loginUser(userInfo));
    navigate("/");
    setUserInfo({ accountId: "", password: "" });
  };

로그인에 실패해도 '/'로 이동한다..
그리고 thunk로 비동기 처리를 해주고 또 ? 또 ? 해야하나 ?이게 맞나 ?

  • extraReducer에 __loginUser가 fulfilled 됐을 때. 함수가 실행되게 한다?
          [__loginUser.fulfilled]: (state, action) => {
            const navigate = useNavigate();
            state.isLoading = false;
            state.users = action.payload;
            navigate('/')
          },

저 부분에 함수가 실행이 안됨 ㅎㅎ useNavigate를 사용할 수 없음. 이유: 컴포넌트가 아니여... 그라믄안대 ......

  1. 해결
// 로그인 실행 함수
  const submitLoginHandler = async (e) => {
    e.preventDefault();
    await dispatch(__loginUser({ userInfo, next: () => navigate("/") }));
    setUserInfo({ accountId: "", password: "" });
  };

// 로그인 thunk 함수
  export const __loginUser = createAsyncThunk(
    "users/loginUser",
    async (payload, thunkAPI) => {
        try {
          const response = await axios.post(`${process.env.REACT_APP_SERVER_URL}/login`, payload.userInfo);
          const {token} = response.headers
          console.log("response",response);
          cookies.set("token", token,{path:'/'})
          return thunkAPI.fulfillWithValue(payload)
        } catch (error) {
          console.log(payload);
          console.log(error);
          return thunkAPI.rejectWithValue(error.response.status)
        }
      }
  );

// login thunk함수 extraReducer 부분
          [__loginUser.fulfilled]: (state, action) => {
            state.isLoading = false;
            state.users = action.payload.userInfo;
            action.payload.next()
          },
  1. 알게된 점

payload로 함수도 보내줄 수 있따...!!!!!!!

dispatch(__loginUser({ userInfo, next: () => navigate("/") }))

{}로 묶어줘서 보내줘야한다.
()=>함수형태로 해야한다.
이름은 next가 아니어도 된다. 내가정해주는거임. 뽑아쓸때 편하려고.

profile
항상 피곤한 인서의 개발블로그

0개의 댓글