Skip to content

Instantly share code, notes, and snippets.

@zhirzh
Last active April 1, 2019 08:23
Show Gist options
  • Save zhirzh/f00c933adfec99e5bcbcac17c4c5a10d to your computer and use it in GitHub Desktop.
Save zhirzh/f00c933adfec99e5bcbcac17c4c5a10d to your computer and use it in GitHub Desktop.
// store.ts
import { combineStore, createStore } from 'redux'
import { todosReducer } from './todos'
import { userReducer } from './user'
const store = createStore(
combineStore({
user: userReducer,
todos: todosReducer,
})
)
export default store
// todos.ts
export interface Todo {
desc: string
done: boolean
}
export type TodosState = ReadonlyArray<Todo>
export interface addTodoAction {
type: 'ADD_TODO'
payload: Todo
}
export interface updateTodoAction {
type: 'UPDATE_TODO'
payload: {
idx: number
todo: Todo
}
}
type TodoActions = addTodoAction | updateTodoAction | removeTodoAction
const initialState: TodosState = []
export interface removeTodoAction {
type: 'REMOVE_TODO'
payload: number
}
export function addTodo(desc: string): addTodoAction {
return {
type: 'ADD_TODO',
payload: {
desc,
done: false,
},
}
}
export function updateTodo(idx: number, todo: Todo): updateTodoAction {
return {
type: 'UPDATE_TODO',
payload: {
idx,
todo,
},
}
}
export function removeTodo(idx: number): removeTodoAction {
return {
type: 'REMOVE_TODO',
payload: idx,
}
}
export function todosReducer(state = initialState, action: TodoActions): TodosState {
switch (action.type) {
case 'ADD_TODO':
return state.concat(action.payload)
case 'UPDATE_TODO':
return state.map((todo, idx) =>
idx === action.payload.idx ? { ...todo, ...action.payload.todo } : todo
)
case 'REMOVE_TODO':
return state.filter((_, idx) => idx !== action.payload)
default:
return state
}
}
// user.ts
export interface UserState {
name: string
age: number
}
export interface setUserNameAction {
type: 'SET_NAME'
payload: string
}
export interface setUserAgeAction {
type: 'SET_AGE'
payload: number
}
export type UserActions = setUserNameAction | setUserAgeAction
const initialState: UserState = {
name: '',
age: 0,
}
export function setUserName(name: string): setUserNameAction {
return {
type: 'SET_NAME',
payload: name,
}
}
export function setUserAge(age: number): setUserAgeAction {
return {
type: 'SET_AGE',
payload: age,
}
}
export function userReducer(state = initialState, action: UserActions): UserState {
switch (action.type) {
case 'SET_NAME':
return {
...state,
name: action.payload,
}
case 'SET_AGE':
return {
...state,
age: action.payload,
}
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment