TS Redux thunk 사용

김수민·2023년 3월 8일
0

TypeScript

목록 보기
8/8

redux-thunk, axios 설치

npm i redux-thunk
npm i axios


컨테이너 컴포넌트 작성

redux 모듈 생성

1. 액션 타입 선언

const 액션타입명='주소';
const GET_PRODUCT='getDataReducer/GET_PRODUCT';

2. 액션 생성 함수 생성

export const 함수명=createStandardAction(액션타입명)<액션타입명의 타입>

3. 타입 지정

type 타입명=타입지정

4. thunk 함수 생성

export const thunk함수명 = (): any => 
async (dispatch: Dispatch) => {
  dispatch했을 때 실행할 구문
    try {
      try했을 때 실행할 구문
    } catch (e) {
      error일때 실행할 구문
    }
};

5. reducer 생성

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;

reducer 연결

Rootreducer 생성

ㄴ최종본

[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.js에 store 생성

  1. store 생성 및 redux middleware를 설치한다.
    ❗ 설치한 store는 Provider의 매개변수로 지정한다.
[index.tsx]
import Thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(Thunk));

root.render(
  <React.StrictMode>
    <Provider store={store}>
        <App />  
    </Provider>
  </React.StrictMode>
);
  1. composeWithDevTools 사용
    devtools 사용을 위해 composeWithDevTools를 사용한다.
[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> )}
)
profile
sumin0gig

0개의 댓글