npm i redux-thunk
npm i axios
const 액션타입명='주소';
const GET_PRODUCT='getDataReducer/GET_PRODUCT';
export const 함수명=createStandardAction(액션타입명)<액션타입명의 타입>
type 타입명=타입지정
export const thunk함수명 = (): any =>
async (dispatch: Dispatch) => {
dispatch했을 때 실행할 구문
try {
try했을 때 실행할 구문
} catch (e) {
error일때 실행할 구문
}
};
function reducer함수 명(state: state타입 ,action: any) {
switch (action.type) {
case 액션타입명:
return {
새로 state가 될 값
}
default:
return state;
}
}
export default getDataReducer;
[modules/getDataReducer.ts]
import axios from "axios";
import { Dispatch } from "redux";
import { API_URL } from "../API/api";
import { deprecated } from "typesafe-actions";
const { createStandardAction } = deprecated;
// 1.액션타입 선언
const GET_PRODUCT='getDataReducer/GET_PRODUCT';
// 2. 액션생성 함수
export const getproduct=createStandardAction(GET_PRODUCT)<productDataType>
// 타입지정
export type productDataType={
no:number,
name:string,
}
export type stateType = {
product: productDataType[]|null;
};
// thunk 함수
export const getThunk = (): any =>
async (dispatch: Dispatch) => {
try {
const response= await axios.get(`${API_URL}/admin/product`);
const data= response.data;
console.log("dispatch됨!");
dispatch({type:GET_PRODUCT, payload:data})
} catch (e) {
alert(e);
}
};
// 초기값 지정
const initialState={
product: null,
}
// 리듀서 함수
function getDataReducer(state: stateType = initialState,action: any) {
switch (action.type) {
case GET_PRODUCT:
return {
...state,
product: action.payload
}
default:
return state;
}
}
export default getDataReducer;
[modules/index.ts]
import { combineReducers } from "redux";
import getDataReducer from "./getDataReducer";
export type rootState = ReturnType<typeof rootReducer>
const rootReducer= combineReducers({getDataReducer});
export default rootReducer;
[index.tsx]
import Thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(Thunk));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
[index.tsx]
import { composeWithDevTools } from '@redux-devtools/extension';
const store= createStore(rootReducer,composeWithDevTools(applyMiddleware(Thunk),));
app.tsx에서 라우터를 사용중인 코드이다.
[index.tsx]
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { applyMiddleware, createStore } from 'redux';
import rootReducer from './modules';
import { composeWithDevTools } from '@redux-devtools/extension';
import Thunk from 'redux-thunk';
const store= createStore(rootReducer,composeWithDevTools(applyMiddleware(Thunk),));
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>
);
reportWebVitals();
useSelector 및 useDispatch를 이용하여 state를 업데이트하거나 업로드 할 수 있다.
const dispatch=useDispatch();
dispatch(Thunk함수명(매개변수))
type datatype=productDataType[]|null
const dispatch=useDispatch();
useEffect(()=>{
dispatch(getThunk())
},[dispatch])
const data:datatype= useSelector((state:rootState)=>state.getDataReducer.product);
return(
{data.map(d=> <div>{d.p_name}</div> )}
)