로그인, 로그아웃, 회원가입을 비동기로 처리하는 이유

이로운·2025년 3월 7일
0

React Native

목록 보기
5/5

현재 내 프로젝트는 로그인 로그아웃 회원가입을 createAsyncThunk를 사용한 비동기로 처리해주고 있다. 어떤게 좋은지 갑자기 궁금했다.

이유

간단히 말하면 서버와의 통신이 필요한 작업이기 때문이다.
즉 API요청을 보내고 응답을 받을 때 까지 시간이 걸리기 때문에 UI가 멈추지 않도록 비동기로 처리해야한다

네트워크 요청이 완료될 때까지 기다려야함

const response = fetch("https://example.com/api/login", {
  method: "POST",
  body: JSON.stringify({ email, password }),
});

위 코드는 서버에 요청을 보내고 응답을 받을 때 까지 시간이 걸린다. 만약 동기로 설정하면 응답을 받을 때까지 앱이 멈춰버리는 수가 있다.

로딩상태 표시 가능

const handleLogin = async () => {
  setLoading(true); // 🔥 로딩 시작
  try {
    const response = await fetch("https://example.com/api/login");
    const data = await response.json();
    console.log("로그인 성공:", data);
  } catch (error) {
    console.log("로그인 실패:", error);
  } finally {
    setLoading(false); // 🔥 로딩 종료
  }
};

서버 응답을 기다리는 동안 로딩중이라는 것을 표시해줄 수 있다.

Redux에서 pending, fulfilled, reject 상태관리

Redux의 createAsyncThunk는 API 요청의 상태를 자동으로 관리해준다 (현재 이와같이 구현되어 있다)

const loginUser = createAsyncThunk("auth/loginUser", async (credentials) => {
  const response = await fetch("https://example.com/api/login", {
    method: "POST",
    body: JSON.stringify(credentials),
  });
  return await response.json();
});

const authSlice = createSlice({
  name: "auth",
  initialState: { loading: false, user: null },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(loginUser.pending, (state) => {
        state.loading = true; // 요청 중 상태
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.loading = false;
        state.user = action.payload;
      })
      .addCase(loginUser.rejected, (state) => {
        state.loading = false;
      });
  },
});

로그아웃은 왜 비동기로 처리할까

AsyncStoreage의 토큰을 파기시켜야하기 때문이다. 이런 경우에 서버에 요청을 보내야하기 때문이다.

profile
개발자가 세상을 구한다

0개의 댓글