Created
December 7, 2022 16:45
-
-
Save CarmeloRicarte/06d430fde20eee2a15bee0f91a8dc467 to your computer and use it in GitHub Desktop.
Template for create a Redux Toolkit slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSlice } from "@reduxjs/toolkit"; | |
import type { PayloadAction } from "@reduxjs/toolkit"; | |
export interface CounterState { | |
counter: number; | |
} | |
const initialState: CounterState = { | |
counter: 0, | |
}; | |
export const counterSlice = createSlice({ | |
name: "counter", | |
initialState, | |
reducers: { | |
increment: (state) => { | |
// Redux Toolkit allows us to write "mutating" logic in reducers. It | |
// doesn't actually mutate the state because it uses the Immer library, | |
// which detects changes to a "draft state" and produces a brand new | |
// immutable state based off those changes | |
state.counter += 1; | |
}, | |
decrement: (state) => { | |
state.counter -= 1; | |
}, | |
incrementByAmount: (state, action: PayloadAction<number>) => { | |
state.counter += action.payload; | |
}, | |
decrementByAmount: (state, action: PayloadAction<number>) => { | |
state.counter -= action.payload; | |
}, | |
}, | |
}); | |
// Action creators are generated for each case reducer function | |
export const { increment, decrement, incrementByAmount, decrementByAmount } = | |
counterSlice.actions; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment