Study/Redux
redux_thunk
Minhhk
2023. 10. 11. 23:50
❗️ 앱에서 비동기 작업 할 때_주로 서버요청 등등 => redux-thunk 사용!!
thunk ?
- 일부 지연된 작업을 수행하는 코드 조각
action 은 객체를 전달하는데, 함수를 dispatch 해야 함으로,
함수를 전달 할 수 있게 하는
redux-thunk를 설치하여 적용하자!
npm i redux-thunk
import thunk from "redux-thunk";
...
const middleware = applyMiddleware(thunk, loggerMiddleware);
1 . 미들웨어에 적용,,
2. reducer 와 action 을 만들어준다
->
reducers/posts.tsx
enum ActionType {
FETCH_POSTS = "FETCH_POSTS",
DELETE_POSTS = "DELETE_POSTS",
}
interface Post {
userId: number;
id: number;
title: string;
}
interface Action {
type: ActionType;
payload: Post[];
}
const posts = (state = [], action: Action) => {
switch (action.type) {
case "FETCH_POSTS":
return [...state, ...action.payload];
default:
return state;
}
};
export default posts;
actions/posts.tsx
export const fetchPost = (): any => async (dispatch: any, getState: any) => {
const res = await axios.get("http://jsonplaceholder.typicode.com/posts");
dispatch({ type: "FETCH_POSTS", payload: res.data });
};
3. 사용할 컴포넌트 에서 dispatch를 해준 뒤, useSelector() 를 이용해 데이터를 꺼낸다.
그리고 아래에서 랜더링~해준다.
const posts: Post[] = useSelector((state: RootState) => state.posts);
useEffect(() => {
dispatch(fetchPost());
}, [dispatch]);
...
return
...
{posts.map((post, i) => (
<li key={i}>{post.title}</li>
))}