redux-thunk는 리덕스에서 비동기 작업을 처리 할 때 가장 많이 사용하는 미들웨어 이다. 이 미들웨어를 사용하면
액션 객체가 아닌 함수를 디스패치 할 수 있다. 즉 액션 대신 함수를 반환하는 액션 크리에이터를 쓸 수 있게 해준다. 파라미터는 dispatch와 getState를 쓴다.(getState는 없으면 굳이 안써도 된다.)
redux-thunk라는 미들웨어는 API호출이 필요할 때 쓴다.
export const fetchData = () => {
// 이 액션 생성자(fetchData)는 함수를 반환한다.
// 함수는 dispatch와 getState를 매개변수로 가진다.
return async function(dispatch, getState) {
const response = await APIadress.get('/data')
// 요청이 완료되면 여기서 직접 dispatch 한다.
dispach ({ type: 'FETCH_DATE', payload: redponse })
}
}
리팩토링 형태
export const fetchData = () => async dispatch => {
const reponse = await APIadress.get('/data');
dispatch({ type: 'FETCH_DATA', payload: response })
}
redux-toolkit은 createAsyncThunk라는 함수를 제공한다.
createAsyncThunk는 createAction처럼 액션 생성 함수이기 때문에 첫 번째 파라미터로 액션명을 받는다. 두 번째 파라미터로 콜백 함수를 작성하여 비동기 로직을 사용한다.
const getEmployees = createAsyncThunk("GET/EMPLOYEES", async () => {
// ajax를 요청하고 promise 객체를 리턴 받는 함수를 여기에 사용합니다.
}),
promise란?
리액트에서 비동기처리에 활용되는 객체. 원활한 데이터 통신을 위해 활용되며 서버에 데이터를 요청했을 때, 데이터를 모두 받아오기전에 웹에 출력하려고 할 때 발생하는 오류를 방지하기 위해 사용.
위의 주석처리된 부분, 비동기 로직이 들어갈 자리에 axios 사용
const getEmployees = createAsyncThunk("GET/EMPLOYEES", async () => {
return axios({
method: "get",
url: "http://dummy.restapiexample.com/api/v1/employees"
});
}),
리듀서와 엮어서 사용
export const action = {
getEmployees: createAsyncThunk("GET/EMPLOYEES", async () => {
return axios({
method: "get",
url: "http://dummy.restapiexample.com/api/v1/employees"
}).then(response => response.data);
}),
};
const initialState = {
employees: [],
};
export const reducer = {
getEmployees: (state, action) => {
state.getEmployees = action.payload.data;
}
};
const employeesReducer = createReducer(initialState, builder => {
builder
.addCase(action.getEmployees.fulfilled, reducer.getEmployees)
});
export default employeesReducer;
리듀서를 사용하는 스토어
import { configureStore } from "@reduxjs/toolkit";
import employeesReducer from "src/store/employees";
export const store = configureStore({
reducer: {
employees: employeesReducer,
},
});