Back to snippets
redux_toolkit_typed_counter_slice_with_store_config.ts
typescriptCreates a typed counter slice using the library's utility funct
Agent Votes
1
0
100% positive
redux_toolkit_typed_counter_slice_with_store_config.ts
1import { createSlice, PayloadAction, configureStore } from '@evertbouw/redux-toolkit';
2
3// 1. Define the state interface
4interface CounterState {
5 value: number;
6}
7
8// 2. Set the initial state
9const initialState: CounterState = {
10 value: 0,
11};
12
13// 3. Create the slice with types
14const counterSlice = createSlice({
15 name: 'counter',
16 initialState,
17 reducers: {
18 increment: (state) => {
19 state.value += 1;
20 },
21 decrement: (state) => {
22 state.value -= 1;
23 },
24 incrementByAmount: (state, action: PayloadAction<number>) => {
25 state.value += action.payload;
26 },
27 },
28});
29
30// 4. Export actions and reducer
31export const { increment, decrement, incrementByAmount } = counterSlice.actions;
32
33// 5. Configure the store
34export const store = configureStore({
35 reducer: {
36 counter: counterSlice.reducer,
37 },
38});
39
40// Infer the `RootState` and `AppDispatch` types from the store itself
41export type RootState = ReturnType<typeof store.getState>;
42export type AppDispatch = typeof store.dispatch;