idillon | d858c18 | 2022-09-16 13:18:26 -0400 | [diff] [blame] | 1 | import { createSlice, PayloadAction } from "@reduxjs/toolkit"; |
| 2 | import type { RootState } from "./store"; |
| 3 | |
| 4 | // Define a type for the slice state |
| 5 | interface appState { |
| 6 | value: number; |
| 7 | } |
| 8 | |
| 9 | // Define the initial state using that type |
| 10 | const initialState: appState = { |
| 11 | value: 0, |
| 12 | }; |
| 13 | |
| 14 | export const appSlice = createSlice({ |
| 15 | name: "app", |
| 16 | // `createSlice` will infer the state type from the `initialState` argument |
| 17 | initialState, |
| 18 | reducers: { |
| 19 | increment: (state) => { |
| 20 | state.value += 1; |
| 21 | }, |
| 22 | decrement: (state) => { |
| 23 | state.value -= 1; |
| 24 | }, |
| 25 | // Use the PayloadAction type to declare the contents of `action.payload` |
| 26 | incrementByAmount: (state, action: PayloadAction<number>) => { |
| 27 | state.value += action.payload; |
| 28 | }, |
| 29 | }, |
| 30 | }); |
| 31 | |
| 32 | export const { increment, decrement, incrementByAmount } = appSlice.actions; |
| 33 | |
| 34 | // Other code such as selectors can use the imported `RootState` type |
| 35 | export const selectCount = (state: RootState) => state.app.value; |
| 36 | |
| 37 | export default appSlice.reducer; |