dispatch가 어떻게 동작하는지 알아본다.
Read - 게시글 읽기 (서버에서 데이터를 불러오는 과정)
// src/components/home/HomeContainer/index.jsx
import { getFollowerPostList } from "../../../actions/followAction";
useEffect(() => {
dispatch(getFollowerPostList());
}, [dispatch]);
dispatch 함수dispatch 함수가 실행이되고 그 안에 있는 getFollowerPostList() 함수가 실행이 된다export const getFollowerPostList = () => async (dispatch, getState) => {
try {
dispatch({ type: FOLLOW_POST_LIST_REQUEST });
const {
userLogin: { userInfo },
} = getState();
const config = {
headers: {
Authorization: `Bearer ${userInfo.user.token}`,
"Content-type": "application/json",
},
};
const { data } = await axios.get(`${API_URL}/post/feed`, config);
dispatch({
type: FOLLOW_POST_LIST_SUCCESS,
payload: data.posts,
});
} catch (error) {
dispatch({
type: FOLLOW_POST_LIST_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
export const getFollowerPostList = () => async (dispatch, getState) => {....
함수가 낯익게 생기지 않았다. 중간에 middleWare 함수가 들어갔기 때문이다. 우리 프로젝트에서는 redux-thunk를 통해서 리덕스의 비동기 작업을 처리한다. 이 미들웨어를 사용하면 액션 객체가 아닌 함수를 디스패치 할 수 있다고한다. 어렵게 여겨진다면 일단은 이 middleWare 함수가 있기 때문에 우리는 redux를 통해서 상태를 관리할 수 있다고 이해하면 좋다.
async (dispatch, getState)
중요한것은 dispatch와 getState를 사용하면 우리가 저장해둔 상태값이 모여있는 store에 데이터를 보낼수도 있고 가지고 올 수도 있다. 우리는 dispatch를 통해서 reducer에 접근할 예정이다.