๐ 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 });
}
};