【React + TypeScript + ReduxToolkit】 가장 간단한 React + TypeScript + ReduxToolkit으로 Let's 비동기 통신

소개


  • 이 기사를 읽으면 React-TypeScript-ReduxToolkit의 Slice 작성부터 비동기 통신까지 이해할 수 있습니다.
  • 설명은 최소한으로 유지해, 코드 베이스로 진행해 갑니다.

  • 막상 React-TypeScript-ReduxToolkit의 환경 구축



    우선은 무엇이든지 커맨드로 React-TypeScript-ReduxToolkit의 환경을 구축한다.
    create-react-app my-app --template redux-typescript
    

    그리고 다음 명령으로 실행
    npm run start もしくは yarn start
    

    이런 화면이 나오면, 개발 환경 구축 완료입니다.



    귀엽다. Redux 로고.
    필자도 이런 생각할 수 있는 사람이 되고 싶다고 합니다…

    Redux-TypeScript template의 내용을 보자.



    그리고 src/feautures 디렉토리를 살펴보자.
    Counter 디렉토리가 들어 있어야 합니다.

    ReduxToolkit의 특징은

    기능마다 Slice라는 덩어리를 만들어 정리해 나가는 것입니다.

    그래서, 새롭게 기능을 추가하고 싶은 경우는 이 template와 같이 features안에 Counter와 같은 Slice를 만들면 OK.

    그럼 비동기 통신의 Slice를 만들어 갑시다.

    비동기 통신 Slice를 만들자!



    기다리지 말고, 비동기 통신의 Slice를 만들어 갑시다.
    그럼, 이름을 fetch로 해, features 디렉토리의 내부에 작성해 주세요.


    그 안에 두 개의 TypeScript 파일을 만듭니다.
  • Fetch.tsx
  • fetchSlice.ts

  • 이런 느낌이 들었나요?



    DOM을 return하는 파일은 확장자를 .tsx로 해, 함수 등 밖에 정의하지 않는 파일은 .ts로 하면 좋은 느낌이 드네요.

    그럼, fetchSlice.ts에서 써 봅시다!
    이번 비동기 통신의 API는 JSONPlaceholder의 것을 사용하였습니다.

    · JSONPlaceholder
    htps : // j 그런 p ぁ세호 l에서 r. ty 피코로. 코m/우세 rs

    그리고 비동기 통신이므로이 아이도 잊지 않고 설치
    npm install axios もしくは yarn add axios
    

    fetchSlice.ts
    
    import {createSlice, createAsyncThunk } from '@reduxjs/toolkit'
    import axios from 'axios'
    import userData from './userData.json'
    import {RootState} from '../../app/store'
    
    type UserDataType = typeof userData
    
    type FetchType = {
      data: UserDataType
    }
    
    export const fetchGetData = createAsyncThunk('fetch/get', async () => {
      const res = axios.get<UserDataType>('https://jsonplaceholder.typicode.com/users')
      return res
    })
    
    const initialState: FetchType = {
      data: userData
    }
    
    export const fetchSlice = createSlice({
      name: 'fetch',
      initialState: initialState,
      reducers: {},
      extraReducers: (builder) => {
        builder.addCase(fetchGetData.fulfilled, (state, action) => {
          return {
            ...state,
            data: action.payload.data
          }
        })
      }
    })
    
    export const selectData = (state: RootState) => state.fetch.data
    
    export default fetchSlice.reducer
    

    이것으로 완성입니다!

    그리고 app/store.ts를 조금 만지십시오.
    import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
    import counterReducer from '../features/counter/counterSlice';
    import fetchReducer from '../features/fetch/fetchSlice'
    export const store = configureStore({
      reducer: {
        counter: counterReducer,
        fetch: fetchReducer
      },
    });
    
    export type RootState = ReturnType<typeof store.getState>;
    export type AppThunk<ReturnType = void> = ThunkAction<
      ReturnType,
      RootState,
      unknown,
      Action<string>
    >;
    
    

    fetchReducer 부분을 추가하기만 하면 됩니다!

    이것으로 Slice를 만들고 Store에 저장할 수 있습니다.

    Fetch.tsx 정보



    그럼, 마지막으로 store에 저장한 값을 컴퍼넌트로부터 꺼내 봅시다!
    import React from 'react';
    import { useSelector, useDispatch } from 'react-redux'
    import { selectData, fetchGetData } from './fetchSlice'
    const Fetch = () => {
        const data = useSelector(selectData)
        const dispatch = useDispatch()
    
        React.useEffect(() => {
            dispatch(fetchGetData())
        }, [])
    
        console.log(data)
        return (
            <div>
                <h1>Fetch</h1>
            </div>
        )
    }
    
    export default Fetch
    
    

    useEffect에서 dispatch를 호출하고 useSelector에서 값을 참조합니다.

    이것으로 ReduxToolkit × TypeScript 비동기 통신 환경 구축이 종료됩니다.

    미안해!

    좋은 웹페이지 즐겨찾기