리액트 - Redux Tunk (2)

이한결·2023년 2월 21일
0

부트 캠프

목록 보기
60/98
post-thumbnail

2월 21일 여정 44일차이다.

Redux Tunk 2부이다. 내가 사용한 코드 예시를 보면서 설명하겠다.

오늘의 Today I Learned

먼저 Json-server를 설치하여 가동시켰다.

{
  "list": []
}

그 다음은 리듀서의 뼈대 작업을 해주었다.



import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  diary: [],
};

export const diary = createSlice({
  name: "diary",
  initialState,
  reducers: {},
});

export const {} = diary.actions;
export default diary.reducer;

스토어 파일에는 앞으로 들어갈 여러 reudcer의 configureStore를 만들어준다.

const store = configureStore({
  reducer: {
    /* 이후에 추가될 여러 리듀서들 */
  },
});

export type RooteState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export default store;

이후에는 다시 리듀서로 돌아와서 Tunk함수를 만든다.

export const __getDiary = createAsyncThunk(
  "diary/getDiary",
  async (_, thunkAPI) => {
    try {
      const data = await axios.get("/list");
      return thunkAPI.fulfillWithValue(data.data);
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);

createAsyncThunk 라는 함수를 통하여 axios를 사용하여 서버와 통신을 한다.
서버와 통신 할 때 상태는 data, isLoading, error로 관리를 하게 된다.
axios.get() (함수)은 Promise를 반환한다. 그래서 반환된 Promise의 fullfilled 또는 rejected된 것을 처리하기위해 async/await 을 추가했다.

요청이 성공하는 경우에 실행되는 부분과 실패했을 때 실행되어야 하는 부분을 나누기 위해 try..catch 구문을 사용하였다.

그 다음은 가져온 데이터를 Store로 dispatch해야 한다.

const initialState: DiaryState = {
  diary: [],
  isLoading: false,
  error: null,
};

const diary = createSlice({
  name: "myDiary",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(__getDiary.pending, (state) => {
      state.isLoading = true;
    });
    builder.addCase(__getDiary.fulfilled, (state, action) => {
      state.isLoading = false;
      state.diary = action.payload;
    });
    builder.addCase(__getDiary.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload;
    });
  },
});

각각의 sate에 따라 isLoading(로딩중) error(에러) diary(사용자 입력 데이터)를 extraRecuders에서 처리해주었다.

만약 __getDiary에서 작업이 fulfilled, 즉 성공하면 로딩중은 false가 되며 sate.diary는 actiton에 있는 payload가 된다.

그 외에 pending 대기중일때와 reject일(실패 혹은 거부) 경우를 각각 처리해준다.

마지막으로

보기에는 복잡해보이지만, 순서만 잘 기억해서 하나씩 차근차근 해내가면 할 수 있다.

profile
평범한 삶을 위하여

0개의 댓글