[Today I Learned] 1월 4주차 day2

suwoncityboyyy·2023년 1월 24일
0

redux- toolkit 다시 공부

설연휴 동안 오랜만에 가족 따라댕기느라 공부 할 시간이 없었다. 그전에는 RN으로 프로젝트 진행하였고 react-query를 통해서 서버 데이터처리를 했다. 그래서인지 thunk에 대한 개념을 다잊어버렸고 감이 사라져버렸다. 요번 프로젝트에서는 thunk를 활용해 구현해야 한다.

미들웨어가 뭐였더라?

기본적으로 리덕스 에서 dispatch를 하면 action이 리듀서로 전달이 되고, 리듀서는 새로운 state를 반환 해 준다. 근데 이과정에서 미들웨어 를 사용하면 우리가 하고 싶은 비동기처리 작업을 할 수 있다.
보통 미들웨어를 사용하는 이유서버와의 통신을 위해서 사용하는 것이 대부분 이다.

redux thunk

redux-thunk는 리덕스에서 서버 데이터 처리 할 때 가장 많이 사용하는 미들웨어이다.
서버 데이터를 처리할 때에는 createAsyncThunk api를 사용한다.

createAsyncThunk 는 Promise의 3가지 상태와 같이 pending, fulfilled, rejected의 상태를 갖습니다.

기본 사용 예시

App.js


  const dispatch = useDispatch();
  const { isLoading, error, todos } = useSelector((state) => state.todos);

  useEffect(() => {
    dispatch(__getTodos());
  }, [dispatch]);

  if (isLoading) {
    return <div>로딩 중....</div>;
  }

  if (error) {
    return <div>{error.message}</div>;
  }

modules/example.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

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

export const __getTodos = createAsyncThunk(
  "todos/getTodos",
  async (payload, thunkAPI) => {
    try {
      const data = await axios.get("http://localhost:3001/todos");
      return thunkAPI.fulfillWithValue(data.data);
    } catch (error) {
      return thunkAPI.rejectWithValue(error);
    }
  }
);

export const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {},
  extraReducers: {
       [__getTodos.pending]: (state) => {
      state.isLoading = true; // 네트워크 요청이 시작되면 로딩상태를 true로 변경.
    },
    [__getTodos.fulfilled]: (state, action) => {
      state.isLoading = false; // 네트워크 요청이 끝났으니, false로 변경.
      state.todos = action.payload; // Store에 있는 todos에 서버에서 가져온 todos를 넣음
    },
    [__getTodos.rejected]: (state, action) => {
      state.isLoading = false; // 에러가 발생했지만, 네트워크 요청이 끝났으니, false로 변경.
      state.error = action.payload; // catch 된 error 객체를 state.error에 넣는다.
    },
  },
});

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

[참고자료]

생활코딩 redux toolkit 비동기작업강좌
리덕스 toolkit 초기설정 벨로그
redux-thunk 공식문서

profile
주니어 개발자 기술노트

0개의 댓글