Skip to content

Instantly share code, notes, and snippets.

@ockam
Forked from schettino/useUserReducer.ts
Created September 29, 2020 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ockam/59a33a17556d6b5cee29b8c84a76a653 to your computer and use it in GitHub Desktop.
Save ockam/59a33a17556d6b5cee29b8c84a76a653 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment