createAsyncThunk

Jaeseok Han·2023년 11월 20일
0

Redux-Toolkit

목록 보기
6/6

async functionality with createAsyncThunk

Redux Toolkit 의 createAsyncThunk를 사용하여 비동기 기능를 처리하는 방법을 알아보고자 한다.

createAsyncThunk

createAsyncThunk는 비동기 작업을 처리하기 위한 Thunk함수를 생성하는데 사용된다. 이를 통해 비동기 작업의 생명주기 이벤트에 대응하는 액션을 쉽게 생성하고, 이에 따른 상태 업데이트를 Reducer에서 처리할 수 있다.

💡 Thunk함수란
리덕스에서 비동기 작업을 수행하거나 특정 조건에 따라 액션을 지연시켜 디스패치하는 함수이다. 리덕스는 기본적으로 동기적인 액션만 처리하므로 비동기작업이 필요한 경우 Thunk 함수를 사용한다.

💡 redux-thunk
리덕스의 미들웨어인 redux-thunk가 활성화 되어 있어야 Thunk 함수를 사용할 수 있다.

extraReducers

Thunk 함수에서 생성된 액션에 따라 상태를 어떻게 업데이트할 지를 정의한다.

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const url = 'https://course-api.com/react-useReducer-cart-project';

export const getCartItems = createAsyncThunk('cart/getCartItems', () => {
  return fetch(url)
    .then((resp) => resp.json())
    .catch((err) => console.log(error));
});

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  extraReducers: {
    [getCartItems.pending]: (state) => {
      state.isLoading = true;
    },
    [getCartItems.fulfilled]: (state, action) => {
      console.log(action);
      state.isLoading = false;
      state.cartItems = action.payload;
    },
    [getCartItems.rejected]: (state) => {
      state.isLoading = false;
    },
  },
});

getCartItems는 비동기 Thunk 함수로 비동기 작업을 수행하고 작업이 성공(fulfilled), 실패(rejected), 진행중(pending)임에 따라 액션을 자동을 생성한다.

isLoading 값을 통해 로딩되는 중임을 표시해준다.

Options

export const getCartItems = createAsyncThunk(
    'cart/getCartItems',
    async (name, thunkAPI) => {
        try {
            const res = await axios(url);
            return res.data;
        } catch (error) {
            return thunkAPI.rejectWithValue('something went wrong')
        }
    }
);
...
 extraReducers: {
        [getCartItems.pending]: (state) => {
            state.isLoading = true;
        },
        [getCartItems.fulfilled]: (state, action) => {
            console.log(action)
            state.isLoading = false;
            state.cartItems = action.payload;
        },
        [getCartItems.rejected]: (state, action) => {
            console.log(action)
            state.isLoading = false;
        },
    },

해당 코드는 getCartItems의 Thunk 함수가 실패할 경우 thunkAPI.rejectWithValue를 통해서 에러 값을 반환한다.

  [getCartItems.rejected]: (state, action) => {
         console.log(action)
         state.isLoading = false;
     },

action.payload 값에 'something went wrong' 이 값이 들어간걸 확인할 수 있다.

The extraReducers "builder callback" notation

빌더 콜백 표기법(builder callback notation)은 Redux Toolkit에서 제공하는 새로운 방식으로 더 간결하고 가독성이 높은 코드를 작성할 수 있게 해준다.


여기서 builder객체는 다양한 메서드를 제공하며 각가의 메서드는 특정 액션에 대한 처리를 정의한다. 이를 통해 addCase 메서드를 사용하여 액션의 성공, 실패, 진행중일 때의 상태 업데이트를 더 간단하게 정의할 수 있다.

const cartSlice = createSlice({
    name : 'cart',
    initialState,
    reducers : {
      ...
    },
    extraReducers: (builder) => {
        builder
          .addCase(getCartItems.pending, (state) => {
            state.isLoading = true;
          })
          .addCase(getCartItems.fulfilled, (state, action) => {
            // console.log(action);
            state.isLoading = false;
            state.cartItems = action.payload;
          })
          .addCase(getCartItems.rejected, (state, action) => {
            console.log(action);
            state.isLoading = false;
          });
      },

0개의 댓글