Home redux-thunk
Post
Cancel

redux-thunk

๐Ÿ“Œ redux-thunk

โœ๏ธ redux-thunk

redux-thunk๋Š” ๋ฆฌ๋•์Šค์—์„œ ๋น„๋™๊ธฐ ์ž‘์—…์„ ์ฒ˜๋ฆฌ ํ•  ๋•Œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๋ฏธ๋“ค์›จ์–ด์ž…๋‹ˆ๋‹ค. ์ด ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ก์…˜ ๊ฐ์ฒด๊ฐ€ ์•„๋‹Œ ํ•จ์ˆ˜๋ฅผ ๋””์ŠคํŒจ์น˜ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. redux-thunk๋Š” ๋ฆฌ๋•์Šค์˜ ์ฐฝ์‹œ์ž์ธ Dan Abramov๊ฐ€ ๋งŒ๋“ค์—ˆ์œผ๋ฉฐ, ๋ฆฌ๋•์Šค ๊ณต์‹ ๋งค๋‰ด์–ผ์—์„œ๋„ ๋น„๋™๊ธฐ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์˜ˆ์‹œ๋ฅผ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.

thunk์˜ ์˜ˆ์‹œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const getComments = () => (dispatch, getState) => {
  // ์ด ์•ˆ์—์„œ๋Š” ์•ก์…˜์„ dispatch ํ•  ์ˆ˜๋„ ์žˆ๊ณ 
  // getState๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ˜„์žฌ ์ƒํƒœ๋„ ์กฐํšŒ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  const id = getState().post.activeId;

  // ์š”์ฒญ์ด ์‹œ์ž‘ํ–ˆ์Œ์„ ์•Œ๋ฆฌ๋Š” ์•ก์…˜
  dispatch({ type: "GET_COMMENTS" });

  // ๋Œ“๊ธ€์„ ์กฐํšŒํ•˜๋Š” ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” getComments ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค.
  api
    .getComments(id) // ์š”์ฒญ์„ ํ•˜๊ณ 
    .then((comments) =>
      dispatch({ type: "GET_COMMENTS_SUCCESS", id, comments })
    ) // ์„ฑ๊ณต์‹œ
    .catch((e) => dispatch({ type: "GET_COMMENTS_ERROR", error: e })); // ์‹คํŒจ์‹œ
};

async/await๋ฅผ ์‚ฌ์šฉ

1
2
3
4
5
6
7
8
9
10
const getComments = () => async (dispatch, getState) => {
  const id = getState().post.activeId;
  dispatch({ type: "GET_COMMENTS" });
  try {
    const comments = await api.getComments(id);
    dispatch({ type: "GET_COMMENTS_SUCCESS", id, comments });
  } catch (e) {
    dispatch({ type: "GET_COMMENTS_ERROR", error: e });
  }
};
This post is licensed under CC BY 4.0 by the author.

Footer ํ•˜๋‹จ๊ณ ์ •

JS[Generator]