0Pricing
React Native Academy · レッスン

createAsyncThunkによる非同期Thunk

createAsyncThunk内でAPIからデータを取得し、sliceのextraReducersでpending、fulfilled、rejectedのライフサイクルを処理して、UIに非同期処理の状態を表示します

「createAsyncThunkによる非同期Thunk」はCoddyKit上の無料React Native Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはReact Native Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 React Native Academyコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Do We Need Async Thunks?

Redux reducers must be pure synchronous functions — they cannot make API calls or run async code. To fetch data from a server and store the result in Redux, we need an async thunk: a function that dispatches plain actions before and after an async operation. Redux Toolkit's createAsyncThunk handles this pattern with minimal boilerplate.

Creating an Async Thunk

createAsyncThunk accepts two arguments: a string action type prefix and a payload creator function that performs the async work and returns the result. It automatically dispatches pending, fulfilled, or rejected actions based on whether the payload creator's promise resolves or rejects.

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const fetchPosts = createAsyncThunk(
  'posts/fetchPosts',          // action type prefix
  async (page: number) => {    // payload creator
    const response = await axios.get('https://api.example.com/posts?page=' + page);
    return response.data;       // this becomes action.payload
  }
);

The Three Lifecycle Actions

For every createAsyncThunk call, RTK automatically creates three action creators: thunk.pending (dispatched when the async call starts), thunk.fulfilled (dispatched with the returned data when it succeeds), and thunk.rejected (dispatched with the error when it fails). You handle each case in extraReducers.

// These are created automatically:
fetchPosts.pending.type   // 'posts/fetchPosts/pending'
fetchPosts.fulfilled.type // 'posts/fetchPosts/fulfilled'
fetchPosts.rejected.type  // 'posts/fetchPosts/rejected'

Handling Lifecycle in extraReducers

Use the builder.addCase pattern inside extraReducers to handle each lifecycle action. In the pending case set a loading flag, in fulfilled store the data and clear loading, and in rejected store the error message and clear loading. This gives every async operation a consistent state machine.

const postsSlice = createSlice({
  name: 'posts',
  initialState: { items: [], status: 'idle', error: null },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchPosts.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchPosts.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.items = action.payload;
      })
      .addCase(fetchPosts.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message ?? 'Unknown error';
      });
  },
});

Dispatching an Async Thunk from a Component

Dispatch an async thunk exactly like a regular action — pass it to dispatch(). The thunk returns a Promise, so you can await it or chain .then() if you need to react after the async operation completes inside the component. Use useEffect to dispatch it on mount.

import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { fetchPosts } from './postsSlice';

export default function PostsScreen() {
  const dispatch = useAppDispatch();
  const { items, status, error } = useAppSelector((s) => s.posts);

  useEffect(() => {
    dispatch(fetchPosts(1));
  }, [dispatch]);

  if (status === 'loading') return <ActivityIndicator />;
  if (status === 'failed') return <Text>{error}</Text>;
  return <FlatList data={items} /* ... */ />;
}

Passing Arguments to the Thunk

The payload creator function receives the first argument passed to the thunk when dispatched, and a second argument called thunkAPI that provides getState, dispatch, rejectWithValue, and more. Use getState to read current Redux state inside the thunk, for example to include an auth token in a request header.

export const createPost = createAsyncThunk(
  'posts/create',
  async (postData: { title: string; body: string }, thunkAPI) => {
    const state = thunkAPI.getState() as RootState;
    const token = state.user.token;
    const response = await axios.post('/posts', postData, {
      headers: { Authorization: 'Bearer ' + token },
    });
    return response.data;
  }
);

Handling Errors with rejectWithValue

By default, the rejected action contains only the serialized error message. If you need to pass a custom error payload — such as an HTTP status code or server-provided error message — use thunkAPI.rejectWithValue() inside a try-catch block. The value you pass becomes action.payload in the rejected case.

export const fetchUser = createAsyncThunk(
  'user/fetch',
  async (userId: string, { rejectWithValue }) => {
    try {
      const response = await axios.get('/users/' + userId);
      return response.data;
    } catch (err: any) {
      return rejectWithValue(err.response.data.message);
    }
  }
);

// In extraReducers:
.addCase(fetchUser.rejected, (state, action) => {
  state.error = action.payload as string; // custom error message
})

Unwrapping the Dispatch Result

Dispatching a thunk returns a special Promise that you can unwrap() to get the fulfilled value or throw the error. This is useful when you need the result directly in the component — for example, navigating to a new screen after a successful API call without storing transient navigation state in Redux.

async function handleSubmit() {
  try {
    const result = await dispatch(createPost({ title, body })).unwrap();
    navigation.navigate('PostDetail', { id: result.id });
  } catch (err) {
    Alert.alert('Error', 'Failed to create post');
  }
}

Cancelling an In-Flight Request

createAsyncThunk supports request cancellation via an AbortController. The thunkAPI.signal is an AbortSignal that you can pass to Axios or Fetch. When the component unmounts or the user navigates away, calling the thunk's abort() method cancels the pending request and dispatches the rejected action with AbortError.

export const fetchData = createAsyncThunk(
  'data/fetch',
  async (_, { signal }) => {
    const response = await axios.get('/data', { signal });
    return response.data;
  }
);

// In component useEffect:
useEffect(() => {
  const promise = dispatch(fetchData());
  return () => promise.abort(); // cancel on unmount
}, []);

Status-Driven UI Patterns

The status field in your slice state acts as a state machine with four values: idle, loading, succeeded, and failed. Pattern-match on this value in your component to show the right UI for each state. This prevents showing stale data and empty lists simultaneously, giving users clear feedback throughout the async lifecycle.

function renderContent() {
  switch (status) {
    case 'idle':
      return <Text>Press button to load</Text>;
    case 'loading':
      return <ActivityIndicator size='large' />;
    case 'succeeded':
      return <FlatList data={items} renderItem={renderItem} />;
    case 'failed':
      return <Text style={styles.error}>{error}</Text>;
  }
}

Multiple Thunks for CRUD Operations

Real apps typically need separate thunks for each HTTP verb. Create one thunk per operation — fetchItems, addItem, updateItem, deleteItem — and handle each in extraReducers. After a successful mutation, update the local items array in the fulfilled handler so the UI stays in sync without re-fetching the entire list.

.addCase(deleteItem.fulfilled, (state, action) => {
  state.items = state.items.filter((item) => item.id !== action.payload);
})
.addCase(addItem.fulfilled, (state, action) => {
  state.items.push(action.payload);
})
.addCase(updateItem.fulfilled, (state, action) => {
  const index = state.items.findIndex((i) => i.id === action.payload.id);
  if (index !== -1) state.items[index] = action.payload;
})

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: createAsyncThunk wraps async operations and dispatches pending/fulfilled/rejected lifecycle actions automatically, extraReducers with builder.addCase handles each lifecycle to update loading and error state, and rejectWithValue lets you pass custom error data to the rejected handler. Next up we explore Zustand, a lightweight alternative to Redux.

よくある質問

「createAsyncThunkによる非同期Thunk」レッスンは無料ですか?

はい。「createAsyncThunkによる非同期Thunk」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、React Native Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 React Native Academyコースには全4レッスンが含まれています。

「createAsyncThunkによる非同期Thunk」で何を学びますか?

createAsyncThunk内でAPIからデータを取得し、sliceのextraReducersでpending、fulfilled、rejectedのライフサイクルを処理して、UIに非同期処理の状態を表示します ブラウザで直接実行するハンズオンコードでReact Native Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

React Native Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのReact Native Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「createAsyncThunkによる非同期Thunk」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このReact Native Academyレッスンでコードを書いて実行できますか?

はい。すべてのReact Native Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Redux StoreとProviderの設定
  2. createSliceによるSliceの作成
  3. useSelectorによるStateの読み取り
  4. createAsyncThunkによる非同期Thunk
← React Native Academyに戻る