Created
March 30, 2019 20:23
-
-
Save schettino/c8bf5062ef99993ce32514807ffae849 to your computer and use it in GitHub Desktop.
Better Reducers with React and Typescript 3.4
This file contains 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 { useReducer } from 'react' | |
export function updateName(name: string) { | |
return <const>{ | |
type: 'UPDATE_NAME', | |
name | |
} | |
} | |
export function addPoints(points: number) { | |
return <const>{ | |
type: 'ADD_POINTS', | |
points | |
} | |
} | |
export function setLikesGames(value: boolean) { | |
return <const>{ | |
type: 'SET_LIKES_GAMES', | |
value | |
} | |
} | |
export const initialState = { | |
name: '', | |
points: 0, | |
likesGames: true | |
} | |
type State = typeof initialState | |
type Action = ReturnType< | |
typeof updateName | typeof addPoints | typeof setLikesGames | |
> | |
function reducer(state: State, action: Action): State { | |
switch (action.type) { | |
case 'UPDATE_NAME': | |
return { ...state, name: action.name } | |
case 'ADD_POINTS': | |
return { ...state, points: action.points } | |
case 'SET_LIKES_GAMES': | |
return { ...state, likesGames: action.value } | |
default: | |
return state | |
} | |
} | |
export default function useUserReducer(state = initialState) { | |
return useReducer(reducer, state) | |
} |
PureScript
data Action
= Increment Int
| Decrement Int
| Reset
reducer :: Action -> Int -> Int
reducer (Increment x) state = state + x
reducer (Decrement x) state = state - x
reducer Reset _ = 0
result :: Int
result = reducer (Decrement 5) 5
🤣 🤣 🤣
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ReactTodoTypesafeState.ts