redux thunk
: ๋ฆฌ๋์ค์์ ๋น๋๊ธฐ์์
์ ์ฒ๋ฆฌํ ์ ์๋๋ก ๋์์ฃผ๋ ๋ฏธ๋ค์จ์ด
๊ธฐ์กด ์ก์ ์์ฑํจ์๋ฅผ ์์ฑํ ๋์๋ async, await๊ณผ ๊ฐ์ ๋น๋๊ธฐ ํจ์๋ฅผ ์์ฑํ ์ ์์
์๋ฌ์ฝ๋
export const fetchData = async () => {
const response = await axios.get('url')
return {
type: 'FETCH_DATA',
payload: response.data
}
}
Error: action must be plain objects. Use custom middleware for async actions
์ด๋ฐ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ์ํด redux-thunk๋ฅผ ์ฌ์ฉํ ์ ์์
export const fetchData = () => {
return async function(dispatch, getState) {
const response = await axios.get('url')
return {
type: 'FETCH_DATA',
payload: response.data
}
}
}
dispatch
์ getState
๋ฅผ ๋ฐ์ ํ์
๊ฐ์ฒด๋ฅผ returnํ๋ ๋์ , ๋ฐ๋ก dispathํ ์ ์์createAsyncThunk
๋ก ์ก์
ํ์
์ ์ง์ ํ๊ณ , ๋น๋๊ธฐํจ์๋ฅผ ์์ฑ
const ํจ์์ด๋ฆ = createAsyncThunk(์ก์
ํ์
์ด๋ฆ, ๋น๋๊ธฐํจ์);
jsonplaceholder์์ ๊ฒ์๊ธ ๋ชฉ๋ก์ ๊ฐ์ ธ์ค๋ ํจ์๋ฅผ ์์ฑํ๋ฉด ์๋์ ๊ฐ์
export const getPosts = createAsyncThunk("getPosts", async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return response.data;
});
reducer๋ฅผ ์์ฑํ ๋ createSlice
์ reducers:
์ ๊ฐ์ ๋น์์ฃผ๊ณ , extraReducers
๋ฅผ ์ฌ์ฉํ๋ค
์๋ ์ํ์ ๋ฐ๋ผ state๊ฐ ์ด๋ป๊ฒ ๋ณํ ์ง ์ง์ ํด์ฃผ๋๋ก ํจ
action.payload
๋ด๊ธฐ๊ฒ ๋จ. ์ด๋ฅผ ํ์ฉํด์ state์ ๊ฐ์ ์ง์ import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"
const initialState = {
entities: [],
loading: false,
};
export const getPosts = createAsyncThunk("getPosts", async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return response.data
});
export const postSlice = createSlice({
name: "posts",
initialState,
reducers: {},
extraReducers: {
[getPosts.pending]: (state) => {
state.loading = true
},
[getPosts.fulfilled]: (state, action) => {
state.loading = false;
state.entities = action.payload
},
[getPosts.rejected]: (state) => {
state.loading = false;
},
},
});
export default postSlice.reducer