createAsyncThunk tự động dispatch pending/fulfilled/rejected — luôn dùng rejectWithValue thay vì throw để error serializable. createAsyncThunk tạo thunk action creator xử lý async logic (API calls), tự động dispatch 3 lifecycle actions: pending (request bắt đầu → show loading), fulfilled (thành công → update data), rejected (thất bại → show error).
Ví dụ
createAsyncThunk('users/fetch', async (userId, { rejectWithValue }) => { try { return await api.getUser(userId) } catch (err) { return rejectWithValue(err.response.data) } })createAsyncThunk automatically dispatches pending/fulfilled/rejected — always use rejectWithValue instead of throw so errors are serializable. createAsyncThunk creates a thunk action creator that handles async logic (API calls), automatically dispatching three lifecycle actions: pending (request started → show loading), fulfilled (success → update data), rejected (failure → show error).
Example
createAsyncThunk('users/fetch', async (userId, { rejectWithValue }) => { try { return await api.getUser(userId) } catch (err) { return rejectWithValue(err.response.data) } })Pitfall: always use rejectWithValue instead of throwing errors directly — otherwise the error object is not serializable and DevTools display it incorrectly.