목차

  1. 데이터를 불러오는 페이지에서 dispatch가 어떻게 동작하는지 알아본다.
  2. Action함수가 어떤 데이터를 참조하고 어떻게 동작하는지 참조한다
  3. user의 토큰은 어떻게 생기는 것이고, 그것을 어떻게 참조하는지 알아본다
  4. get요청을 했을 때의 결과가 어떻게 reducer에 저장이 되는지 파악한다

스크린샷 2022-03-15 08.17.02.png

Read - 게시글 읽기 (서버에서 데이터를 불러오는 과정)

Read - View

// src/components/home/HomeContainer/index.jsx

import { getFollowerPostList } from "../../../actions/followAction";

useEffect(() => {
    dispatch(getFollowerPostList());
  }, [dispatch]);
  1. 컴포넌트가 렌더링과 동시에 가장 먼저 실행이 되는 함수는 바로 dispatch 함수
  2. dispatch 함수가 실행이되고 그 안에 있는 getFollowerPostList() 함수가 실행이 된다

Read - Action

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)

중요한것은 dispatchgetState를 사용하면 우리가 저장해둔 상태값이 모여있는 store에 데이터를 보낼수도 있고 가지고 올 수도 있다. 우리는 dispatch를 통해서 reducer에 접근할 예정이다.

try....catch