반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

리덕스 툴킷 TS로 리액트와 연동하기(기본 폴더 구조) 본문

인프런, 유데미/Redux

리덕스 툴킷 TS로 리액트와 연동하기(기본 폴더 구조)

5_hyun 2022. 11. 28. 03:00

CRA로 RTK도 같이 설치하기

npx create-react-app my-app --template redux-typescript

이 명령어를 입력하면 리액트 폴더를 만들 때 Redux-ToolKit도 같이 설치하게 된다.

설치된 초기 코드

https://github.com/5hyun/redux_study/tree/main/RTK

 

GitHub - 5hyun/redux_study

Contribute to 5hyun/redux_study development by creating an account on GitHub.

github.com

코드를 보기 위해서는 위 깃허브를 참고하면 된다.

중요하게 볼 폴더

appfeatures 폴더를 참고하면 리덕스 툴킷 공부에 도움이 될것이다.

 

-app

app에는 data를 저장하는 store.ts, data를 가져오고 변경할 수 있는 hooks.ts가 있다.

 

-features

features 폴더에서 주목해야하는 파일은 counterAPI.ts와 counterSlice.ts이 있다.

counterAPI.ts는 action 역할을 하는 파일, counterSlice.ts는 reducer 역할을 하는 파일이라고 보면 된다.

적용 예시

-참고 글

https://shortcoding.tistory.com/399

 

redux-toolkit

redux-toolkit redux-toolkit에는 immer, thunk, redux 등 개발자들이 많이 사용하는 라이브러리가 기본적으로 내장되어있다. -공식 사이트 https://redux-toolkit.js.org/introduction/getting-started Getting Started | Redux Toolkit

shortcoding.tistory.com

아래 내용을 읽기 전에 위 글을 보고오면 훨씬 더 잘 이해가 될 것이다.

redux 폴더

redux 폴더는 위에 설치했던 기본 코드를 폴더 구조만 변경하고 그대로 가져왔다.

actions 폴더

-actions/TestAPI.ts

import { createAsyncThunk } from '@reduxjs/toolkit';

const delay = (time: number, value: object) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(value);
    }, time);
  });

export const addValue = createAsyncThunk('test/add', async () => {
  return await delay(500, {
    value: 10,
  });
});

비동기 혹은 외부와 연동하여 값을 가져오기 위한 action들을 모아둔 actions이다.

이 파일에서는 백엔드와 연동이 되어있지 않기 때문에 value를 10로 받아왔다고 가정을 했다.

reducers 폴더

-reducers/TestSlice.ts

import { createSlice } from '@reduxjs/toolkit';
import { addValue } from '../actions/TestAPI';
import { RootState } from '../redux/store';

export interface TestState {
  value: number;
}

const initialState: TestState = {
  value: 0,
};

export const testSlice = createSlice({
  name: 'test',
  initialState,
  reducers: {
    resetValue: (state) => {
      state.value = 0;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(addValue.fulfilled, (state, action: any) => {
      state.value = action.payload.value;
    });
  },
});

export const { resetValue } = testSlice.actions;
export const testCount = (state: RootState) => state.counter.value;

export default testSlice.reducer;

reducers 폴더 안의 TestSlice.ts에는 reducers와 extraReducers로 나눠서 slice를 만들어주었다.

reducers에서는 value를 0으로 초기화하는 action인 resetValue,

extraReducers에서는 Actions 폴더에서 받아온 값을 가져오는 action을 만들었다.

 

-내가 헷갈렸던 개념

위에 actions 폴더에서 value를 10으로 가져왔다고 가정을 했다. 근데 이 값을 extraReducer에서 어떻게 가져오는지 헷갈렸다. 

이 값을 가져오기 위해서는 action.payload를 활용해서 가져왔어야 한다. 그리고 action의 타입을 any로 했기 때문에 이 부분은 나중에 다시 공부하여 타입을 지정해줘야 한다.

리액트 파일에서 값 가져오기

  const value = useAppSelector(testCount);
  const dispatch = useAppDispatch();

value는 useAppSelector 훅스를 통해 기본 state 값을 가져와준다.

dispatch는 useAppDispatch 훅스를 통해 action을 실행할 수 있다.

 

<AddRoadBtn onClick={() => dispatch(addValue())}>10증가</AddRoadBtn>
<AddRoadBtn onClick={() => dispatch(resetValue())}>리셋</AddRoadBtn>

dispatch를 활용하면 리덕스를 통해 값을 변경할 수 있다.

728x90
반응형
Comments