Redux-Toolkit

최스탑·2022년 8월 14일
0

Redux-Toolkit 이란?

  • Redux를 조금 더 간결하고 쉽게 사용하기 위해 만들어졌다.
  • Redux를 사용할 때의 복잡한 스토어 설정, 추가로 설치해야 하는 패키지들 등의 단점을 보완한다.
    즉, Redux의 복잡도를 낮추고 사용성을 높일 수 있다.

✅ configureStore

  • Redux의 CreateStore 함수를 추상화
  • 설정시 redux-thunk와 DevTools를 제공

✅ createSlice

  • createSlice 함수는 선언한 slice의 name에 따라서 액션 생성자, 액션 타입, 리듀서를 자동으로 생성
    따라서, createAction이나 createReducer를 사용하지 않아도 된다.
/* store/slices/todoSlice.ts */

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface TodoItem {
  id: number,
  title: string,
  checked: boolean
}

export interface CommonState {
  todoList: TodoItem[]
}

const initialState: CommonState = {
  todoList: []
};

export const todoSlice = createSlice({
  name: 'todo',
  initialState,
  reducers: {
    setTodo(state, action: PayloadAction<TodoItem[]>) {
      state.todoList = action.payload;
    }
  }
});

export const { setTodo } = todoSlice.actions;

export default todoSlice;

✅ createAsyncThunk

  • createAsyncThunk 함수는 비동기 액션을 생성할 때 사용
  • 액션 타입을 지정하는 문자열과 프로미스를 반환하는 콜백 함수를 파라미터로 사용하여 생성
  • 실제 사이드 프로젝트를 진행하며 쪽지 리스트 GET 기능에서 활용한 코드
//쪽지 리스트 가져오기
export const getMsgListDB = createAsyncThunk(
  'msg/communicator',
  async (data, thunkAPI) => {
    try {
      await msgApis.getMsg().then((res) => {
        console.log(res);
        const newMsgList: Array<MsgList> = [];

        res.data.data?.map((msg: any) => {
          
          newMsgList.push({
            sender: msg.sender.username,
            senderId: msg.sender.userId,
            receiver: msg.receiver.username,
            content: msg.content,
            unReadCount: msg.unReadCount,
          });
        });
        thunkAPI.dispatch(setMsgList(newMsgList));
      });
    } catch (error) {
      console.log(error);
    }
  }
);

Ref.🙏
https://freestrokes.tistory.com/161

profile
try & catch

0개의 댓글