createAsyncThunk

2023. 1. 17.·🎨 프론트엔드 공부/기타

📍Async Thunk Function

- 전체 유저 리스트를 fetch하는 fetchUsers 흐름

createAsyncThunk 흐름도

📍createAsyncThunk

- 코드 예시

interface MyData {
  // ...
}

const fetchUserById = createAsyncThunk(
  'users/fetchById',
  // 액션 크리에이터 함수의 매개변수에는 typing 필요
  async (userId: number) => {
    const response = await fetch(`https://reqres.in/api/users/${userId}`)
    // Inferred return type: Promise<MyData>
    return (await response.json()) as MyData
  }
)

// the parameter of `fetchUserById` is automatically inferred to `number` here
// and dispatching the resulting thunkAction will return a Promise of a correctly
// typed "fulfilled" or "rejected" action.
const lastReturnedAction = await store.dispatch(fetchUserById(3))

 

 

1️⃣매개변수1 : typePrefix

- 타입 : string

- 액션 타입의 접두사

 

뒤에 아래 키워드들이 붙을 것임

- pending : 비동기 작업을 시작하기 전의 상태

- fulfilled : 비동기 작업이 끝나면 생성

- rejected : 비동기 작업 중 에러 발생하면 생성

 

각각의 3가지 상태 별로 reducer가 필요 -> extraReducer에 각각 만들어주면됨!

- 동기적 작업은 reducers

- 비동기적 작업은 extraReducers

 

2️⃣매개변수2 : action creator

- 비동기 작업을 처리하는 action을 만드는 함수

- 비동기 함수이므로 async를 붙여줘야 함

 

⭐action creator 함수의 매개변수에는 typing 필요

(다른 곳엔 굳이 typing 필요 없음)

 

📍참고

https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk

 

Usage With TypeScript | Redux Toolkit

 

redux-toolkit.js.org

 

'🎨 프론트엔드 공부/기타' 카테고리의 다른 글
  • queries, mutations
  • [RTK Query] createApi
  • Container/Presentational 패턴
  • Redux의 3가지 규칙
지식물원
지식물원
지식이 자라는 식물원!
  • 지식물원
    지식물원
    지식물원
  • 전체
    오늘
    어제
    • 분류 전체보기 (510)
      • 🎨 프론트엔드 공부 (247)
        • JS & TS (86)
        • HTML & CSS (22)
        • React & Next (49)
        • Vue & Nuxt (22)
        • 기타 (68)
      • 🤓 기술 학습 & 공부 기록 (116)
        • Node.js (0)
        • Python (37)
        • 백엔드 (0)
        • 딥러닝 (1)
        • 컴퓨터 일반 (72)
        • 개발 인프라 (6)
      • 👨‍💻 프로젝트 경험 (6)
        • Work (0)
        • Toy (6)
      • ⚙️ 개발 팁 & 노하우 (21)
        • 프론트엔드 (6)
        • 기타 (15)
      • ☕️ 커리어 & 인터뷰 준비 (88)
        • 코딩 테스트 (88)
      • 📰 기술 트렌드 & 생각 정리 (4)
      • 📚 기타 (25)
        • 마케팅 (15)
        • 비개발서적 (10)
  • 블로그 메뉴

    • 태그
  • 링크

  • 공지사항

    • 모바일 접속 시 코드 하이라이팅 깨질 때
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
지식물원
createAsyncThunk
상단으로

티스토리툴바