|
| 1 | +// This file demonstrates typical usage of Redux Toolkit's createSlice function |
| 2 | +// for defining reducer logic and actions, as well as related thunks and selectors. |
| 3 | + |
| 4 | +import type { PayloadAction } from "@reduxjs/toolkit" |
| 5 | +import { createAsyncThunk, createSlice } from "@reduxjs/toolkit" |
| 6 | +import type { AppThunk, RootState } from "../../app/store" |
| 7 | +import { fetchCount } from "./counterAPI" |
| 8 | + |
| 9 | +// Define the TS type for the counter slice's state |
| 10 | +export interface CounterState { |
| 11 | + value: number |
| 12 | + status: "idle" | "loading" | "failed" |
| 13 | +} |
| 14 | + |
| 15 | +// Define the initial value for the slice state |
| 16 | +const initialState: CounterState = { |
| 17 | + value: 0, |
| 18 | + status: "idle", |
| 19 | +} |
| 20 | + |
| 21 | +// Slices contain Redux reducer logic for updating state, and |
| 22 | +// generate actions that can be dispatched to trigger those updates. |
| 23 | +export const counterSlice = createSlice({ |
| 24 | + name: "counter", |
| 25 | + initialState, |
| 26 | + // The `reducers` field lets us define reducers and generate associated actions |
| 27 | + reducers: { |
| 28 | + increment: state => { |
| 29 | + // Redux Toolkit allows us to write "mutating" logic in reducers. It |
| 30 | + // doesn't actually mutate the state because it uses the Immer library, |
| 31 | + // which detects changes to a "draft state" and produces a brand new |
| 32 | + // immutable state based off those changes |
| 33 | + state.value += 1 |
| 34 | + }, |
| 35 | + decrement: state => { |
| 36 | + state.value -= 1 |
| 37 | + }, |
| 38 | + // Use the PayloadAction type to declare the contents of `action.payload` |
| 39 | + incrementByAmount: (state, action: PayloadAction<number>) => { |
| 40 | + state.value += action.payload |
| 41 | + }, |
| 42 | + }, |
| 43 | + // The `extraReducers` field lets the slice handle actions defined elsewhere, |
| 44 | + // including actions generated by createAsyncThunk or in other slices. |
| 45 | + extraReducers: builder => { |
| 46 | + builder |
| 47 | + // Handle the action types defined by the `incrementAsync` thunk defined below. |
| 48 | + // This lets the slice reducer update the state with request status and results. |
| 49 | + .addCase(incrementAsync.pending, state => { |
| 50 | + state.status = "loading" |
| 51 | + }) |
| 52 | + .addCase(incrementAsync.fulfilled, (state, action) => { |
| 53 | + state.status = "idle" |
| 54 | + state.value += action.payload |
| 55 | + }) |
| 56 | + .addCase(incrementAsync.rejected, state => { |
| 57 | + state.status = "failed" |
| 58 | + }) |
| 59 | + }, |
| 60 | +}) |
| 61 | + |
| 62 | +// Export the generated action creators for use in components |
| 63 | +export const { increment, decrement, incrementByAmount } = counterSlice.actions |
| 64 | + |
| 65 | +// Export the slice reducer for use in the store configuration |
| 66 | +export default counterSlice.reducer |
| 67 | + |
| 68 | +// Selector functions allows us to select a value from the Redux root state. |
| 69 | +// Selectors can also be defined inline in the `useSelector` call |
| 70 | +// in a component, or inside the `createSlice.selectors` field. |
| 71 | +export const selectCount = (state: RootState) => state.counter.value |
| 72 | +export const selectStatus = (state: RootState) => state.counter.status |
| 73 | + |
| 74 | +// The function below is called a thunk, which can contain both sync and async logic |
| 75 | +// that has access to both `dispatch` and `getState`. They can be dispatched like |
| 76 | +// a regular action: `dispatch(incrementIfOdd(10))`. |
| 77 | +// Here's an example of conditionally dispatching actions based on current state. |
| 78 | +export const incrementIfOdd = (amount: number): AppThunk => { |
| 79 | + return (dispatch, getState) => { |
| 80 | + const currentValue = selectCount(getState()) |
| 81 | + if (currentValue % 2 === 1) { |
| 82 | + dispatch(incrementByAmount(amount)) |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +// Thunks are commonly used for async logic like fetching data. |
| 88 | +// The `createAsyncThunk` method is used to generate thunks that |
| 89 | +// dispatch pending/fulfilled/rejected actions based on a promise. |
| 90 | +// In this example, we make a mock async request and return the result. |
| 91 | +// The `createSlice.extraReducers` field can handle these actions |
| 92 | +// and update the state with the results. |
| 93 | +export const incrementAsync = createAsyncThunk( |
| 94 | + "counter/fetchCount", |
| 95 | + async (amount: number) => { |
| 96 | + const response = await fetchCount(amount) |
| 97 | + // The value we return becomes the `fulfilled` action payload |
| 98 | + return response.data |
| 99 | + }, |
| 100 | +) |
0 commit comments