
//redux-saga도 있지만 큰규모가 아니라면 thunk쓰면 됨
npm install redux-thunk
import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk';
// store에 미들웨어 파라미터 추가해서 보내줌
let store = createStore(productReducer, applyMiddleware(thunk));
function getProducts() {
// 함수리턴, 매개변수 2개, getState는 현재 state 받아볼 수 있음
return async (dispatch,getState) => {
// 처리할 비동기 작업 작성
let url = ""
let response = await fetch(url)
let data = await response.json
// 미들웨어 -> reducer
dispatch({type: "GET_PRODUCT_SUCCESS"},payload(data))
};
}
// 객체에 함수를 담아서 반환 => action이 여러개가 될 것이기 때문에
export const productAction = {getProducts};
import productAction from '../redux/actions/productAction'
import { useDispatch, useSelector } from 'react-redux'
const ProductAll = () => {
// 미들웨어 거쳐 리듀서 처리후 저장된 store에서 state값 들고오기
const productList = useSelector((state) => state.productList);
const dispatch = useDispatch();
const getProducts = () =>{
// 컴포넌트 -> 미들웨어
dispatch(productAction.getProducts());
}
}
let initialState = {
productList: [],
};
function productReduucer = (state=initialState, action) => {
let {type,payload} = action;
switch(type) {
case 'GET_PRODUCT_SUCCESS':
return {...state, productList: payload.data};
deffault:
return {...state};
}
}
export default productReducer;
- reducer 파일이 여러개인 경우 하나로 통합해서 store에 넣어줘야 함
redux > store.js
import { createStore, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk';
// rootReducer는 임의로 붙여준 이름, index파일은 기본 파일이라 자동으로 찾아감
import rootReducer from "./reducer"
let store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
redux > reducers > index.js
import { combineReducers } from 'redux';
import authenticateReducer from './authenticateReducer';
import productReducer from './productReducer';
export default combineReducers({
auth: authenticateReducer,
product: productReducer,
});