[1] TIL : 개념 정리
A. Redux Thunk
1. 미들웨어
(1) interceptor - 중간에서 어떤 역할을 하는 것들
1) action을 보내기 전과 후에 추가적인 로직을 실행할 수 있음. dispatch 전/후에
2. useEffect
(1) 통신
(2) 동기화
3. dispatch
(1) Redux
1) 객체 형태만 가능했음.
(2) RTK
1) 함수로 가능해짐
2) dispatch로 전역 데이터를 세팅
3) store를 구성하는 게 목적, useSelector로 사용하는 것이 목적
4) 중점적으로 봐야하는 것 = createSlice가 가장 중요함
(3) createSlice
1) ~~~Slice : reducer를 대체
2) 작동하는 과정
i. reducer를 만들어 바깥으로 내보냄
ii. rootReducer => createStore => index, app.jsx에 부여
iii. 내부 컴포넌트들이 이 영향을 받도록!
3) 툴킷 쓰기 전에 했던 모든 걸 압축한 것
4) RTK가 제공하는 함수
input : 객체 - key , value pair
5) 순수 redux
action creator, reducer
6) RTK도 동일함.
- return : todosSlice 객체 - actions, reducers
- 직접 만들지 않더라도 알아서 만들어준다
7) initialState => todos 배열 + 비동기적 상태
(4) createAsyncThunk
1) string, 비동기함수
2) 객체를 보유
상태에 따라 pending, fulfilled, rejected
3) 비동기 통신 : try ~ catch
4) catch에서 fulfillWithValue로 보내면 fulfilled로 감
5) 호출이 된 순간이 pending, pending은 별도의 로직이 없음.
6) 요청이 시작됐으면 pending : isLoading => true
7) __getTodos => 외부에서 dispatch
8) data든 error든 action.payload
9) todos 대신 todo로 작성했으면 오류 => rejected로
(5) extraReducer vs reducer
1) extraReducer : 비동기
- 외부적인 상태 변화 : extraReducer
- initalState를 변경시키기위해, 비동기 통신
- 자동으로 처리될 수 없는 외부 action은 reducer에서 처리할 수 없음
=> createAsyncThunk의 extraReducer에서 처리
- actions : createSlice 내부에서 만든 action이 아니라 바깥에서 선언된 것들
=> extraReducer에 들어와서 내부 state의 변화에 관여함
2) reducer : 내부적인 상태 변화
- 일반적인 전역상태, 자동으로 생성된 action creator로 인해 접수된 변경 건 => dispatch가 일어난 건
(6) extraReducer의 형태 변화
1) RTK 2.0부터 createSlice.extraReducers에서 extraRedcuer case를 추가할 때, 객체로 표기하는 방법에서 builder callback 함수로 표기하는 방법으로 바뀌어서 아래와 같은 오류가 발생
The object notation for `createSlice.extraReducers` has been removed. Please use the ‘builder callback’ notation instead: https://redux-toolkit.js.org/api/createSlice
createSlice | Redux Toolkit
redux-toolkit.js.org
Migrating to RTK 2.0 and Redux 5.0 | Redux
redux.js.org
위 링크를 참고하여 수정하였더니 오류가 해결됨.
extraReducers: (builder) => {
builder.addCase(__getTodos.pending, (state, action) => {pendig시 로직}
builder.addCase(__getTodos.fulfilled, (state, action) => {fulfilled시 로직}
builder.addCase(__getTodos.rejected, (state, action) => {rejected시 로직}
}
3) 객체 형태로 표현하고 싶으면 RTK를 2.0 이전 버젼으로 downgrade하면 됨
yarn add react-redux @reduxjs/toolkit@1.5.0
'개발일지' 카테고리의 다른 글
20240222 TIL #42 (2) | 2024.02.27 |
---|---|
20240221 TIL #41 (2) | 2024.02.27 |
20240219 TIL #39 (0) | 2024.02.27 |
20240216 TIL #38 (0) | 2024.02.22 |
20240215 TIL #37 (0) | 2024.02.22 |