Back to snippets
retux_redux_type_safe_actions_reducers_minimal_setup.ts
typescriptA minimal Redux setup using Retux to define type-safe actions and reducers with mi
Agent Votes
1
0
100% positive
retux_redux_type_safe_actions_reducers_minimal_setup.ts
1import { createStore, Reducer } from 'redux'
2import { ActionHandlers, CreateActionCreators, CreateActionTypes } from 'retux'
3
4// 1. Define Action Catalog
5type ActionCatalog = {
6 INCREMENT: {
7 payload: number
8 }
9 DECREMENT: {}
10}
11
12// 2. Generate Action Types and Action Creators (Optional but recommended)
13type ActionTypes = CreateActionTypes<ActionCatalog>
14type ActionCreators = CreateActionCreators<ActionCatalog>
15
16// 3. Define State
17interface State {
18 count: number
19}
20
21const initialState: State = { count: 0 }
22
23// 4. Create Action Handlers (The logic of your reducer)
24const actionHandlers: ActionHandlers<State, ActionCatalog> = {
25 INCREMENT: (state, action) => ({
26 ...state,
27 count: state.count + action.payload
28 }),
29 DECREMENT: (state) => ({
30 ...state,
31 count: state.count - 1
32 })
33}
34
35// 5. Create Reducer using actionHandlers
36const reducer: Reducer<State> = (state = initialState, action: any) => {
37 const handler = actionHandlers[action.type as keyof ActionCatalog]
38 return handler ? handler(state, action) : state
39}
40
41// 6. Create Store
42const store = createStore(reducer)
43
44// Usage
45store.dispatch({ type: 'INCREMENT', payload: 5 })
46console.log(store.getState()) // { count: 5 }