Skip to content

Instantly share code, notes, and snippets.

@avilde
Created August 12, 2021 06:24
Show Gist options
  • Select an option

  • Save avilde/a1525a2123e7e4b1b1d2bb6e517433f8 to your computer and use it in GitHub Desktop.

Select an option

Save avilde/a1525a2123e7e4b1b1d2bb6e517433f8 to your computer and use it in GitHub Desktop.
Redux State Example
import { BalanceActionType, AddAction, WithdrawAction } from "./types"
export const add = (amount: number): AddAction => ({
type: BalanceActionType.ADD,
payload: amount,
})
export const withdraw = (amount: number): WithdrawAction => ({
type: BalanceActionType.WITHDRAW,
payload: amount,
})
import { BalanceAction, BalanceActionType, BalanceState } from "./types"
const initialState: BalanceState = {
balance: 1000,
}
export const balanceReducer = (
state: BalanceState = initialState,
action: BalanceAction,
): BalanceState => {
switch (action.type) {
case BalanceActionType.ADD:
return { ...state, balance: state.balance + action.payload }
case BalanceActionType.WITHDRAW:
return { ...state, balance: state.balance - action.payload }
default:
return state
}
}
import { combineReducers, createStore } from "redux"
import { balanceReducer } from "./reducers"
import { BalanceState } from "./types"
const rootReducer = combineReducers({
balance: balanceReducer,
})
export interface State {
balance: BalanceState
}
export const store = createStore(rootReducer, undefined)
import { Action } from "redux"
export interface BalanceState {
balance: number
}
export enum BalanceActionType {
ADD = "ADD",
WITHDRAW = "WITHDRAW",
}
export interface AddAction extends Action {
type: BalanceActionType.ADD
payload: number
}
export interface WithdrawAction extends Action {
type: BalanceActionType.WITHDRAW
payload: number
}
export type BalanceAction = AddAction | WithdrawAction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment