Skip to content

Instantly share code, notes, and snippets.

@jonra1993
Last active March 14, 2021 19:39
Show Gist options
  • Save jonra1993/813802f2b4c9b843680924fa109bd44e to your computer and use it in GitHub Desktop.
Save jonra1993/813802f2b4c9b843680924fa109bd44e to your computer and use it in GitHub Desktop.
counter slice for redux toolkit
import { createSlice } from '@reduxjs/toolkit';
/* STATE */
const initialState = {
counter: 5,
};
const slice = createSlice({
name: 'counter',
initialState,
reducers: {
incrementCounter(state) {
state.counter = state.counter + 1;
},
decrementCounter(state, action) {
state.counter = state.counter - 1;
},
setCounter(state, action) {
const newValue = action.payload;
state.counter = newValue;
},
}
});
export const reducer = slice.reducer;
/* ACTIONS */
export const incrementCounterAction = () => async (dispatch) => {
dispatch(slice.actions.increment());
};
export const decrementCounterAction = () => async (dispatch) => {
dispatch(slice.actions.decrementCounter());
};
export const setCounterAction = (newValue) => async (dispatch) => {
dispatch(slice.actions.setCounter(newValue));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment