Redux 로깅 미들웨어 생성하기

루트경로에 있는 index.tsx 파일에 미들웨어를 생성하고 등록합니다.
Redux Thunk
axios 설치
npm install axios --save
위 명령어를 통해 axios 설치합니다.
posts데이터를 위한 요청

App.tsx파일의 추가코드입니다. posts데이터를 위한 요청 보냈습니다.

에러가 굉장히 많이 나올 겁니다.
에러 나는 이유는 아래와 같습니다.
Actions은 객체여야 하는데 현재는 함수를 dispatch하고 있습니다. 그러기 때문에 에러가 생깁니다.
에러 해결책은 아래와 같습니다.
함수를 dispatch할 수 있게 해주는 redux-thunk 미들웨어를 설치해서 사용하면 됩니다.
npm install redux-thunk --save
이 명령어를 사용해서 redux-thunk 설치합니다.

루트경로에 있는 index.tsx파일의 추가 코드입니다. middleware에 thunk도 적용합니다.
posts 데이터 화면에 표출



App.tsx의 추가 코드입니다.
actions들은 따로 분리
지저분해서 actions들은 actions폴더로 분리하겠습니다.

App.tsx의 fetchPosts부분을 src폴더 안에 actions폴더 안에 posts.tsx파일로 이동합니다.
import axios from 'axios';
export const fetchPosts = ():any => {
return async function fetchPostsThunk(dispatch: any, getState: any) {
const res = await axios.get("https://jsonplaceholder.typicode.com/posts")
dispatch({type: 'FETCH_POSTS', payload: res.data})
}
}
rc폴더 안에 actions폴더 안에 posts.tsx파일의 최종 코드입니다.
modern ES2015 형태로 변경
import axios from 'axios';
export const fetchPosts = (): any => async (dispatch: any, getState: any) => {
const res = await axios.get("https://jsonplaceholder.typicode.com/posts")
dispatch({type: 'FETCH_POSTS', payload: res.data})
}
rc폴더 안에 actions폴더 안에 posts.tsx파일이 더 깔끔한 현태로 변경해준 겁니다.
'배워서 따라하는 포플 > react-redux를 이용한 앱' 카테고리의 다른 글
| Redux앱(2) - ToDo 앱 추가 (0) | 2023.09.23 |
|---|---|
| Redux앱(1) - 카운트 앱 생성 (0) | 2023.09.23 |