Skip to content

Instantly share code, notes, and snippets.

@schettino
Created March 30, 2019 20:23
Show Gist options
  • Save schettino/c8bf5062ef99993ce32514807ffae849 to your computer and use it in GitHub Desktop.
Save schettino/c8bf5062ef99993ce32514807ffae849 to your computer and use it in GitHub Desktop.
Better Reducers with React and Typescript 3.4
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)
}
@Ja-rek
Copy link

Ja-rek commented Apr 14, 2020

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