Last active
December 11, 2021 18:55
-
-
Save jasonleehodges/78d5bdbad332ef51976de2cadabb06fc to your computer and use it in GitHub Desktop.
Testable Redux Reducer
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 { | |
PayloadAction, | |
createReducer, | |
} from "@reduxjs/toolkit"; | |
import { increment, decrement, incrementByAmount, incrementAsync } from "./actions"; | |
export interface CounterState { | |
value: number; | |
status: "idle" | "loading" | "failed"; | |
} | |
const initialState: CounterState = { | |
value: 0, | |
status: "idle", | |
}; | |
export const testableCounterReducer = createReducer(initialState, (builder) => | |
builder | |
.addCase(increment, (state) => ({ ...state, value: state.value + 1 })) | |
.addCase(decrement, (state) => ({ ...state, value: state.value - 1 })) | |
.addCase(incrementByAmount, (state, action: PayloadAction<number>) => ({ | |
...state, | |
value: state.value + action.payload, | |
})) | |
.addCase(incrementAsync.pending, (state) => ({ | |
...state, | |
status: "loading", | |
})) | |
.addCase(incrementAsync.fulfilled, (state, action) => ({ | |
...state, | |
status: "idle", | |
value: state.value + action.payload, | |
})) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment