Move reducer out of store.ts

master
Jason Zhu 2023-03-02 17:23:38 +11:00
parent af8bc8c78e
commit 7586a1b2a4
3 changed files with 62 additions and 62 deletions

View File

@ -3,7 +3,7 @@ import { useSelector, useDispatch } from "react-redux";
import Todo from "./Todo"; import Todo from "./Todo";
import {TodoItem} from "./types"; import {TodoItem} from "./types";
import { ADD_TODO, TOGGLE_TODO, DELETE_TODO } from "./store"; import { ADD_TODO, TOGGLE_TODO, DELETE_TODO } from "./reducers";
function App() { function App() {
const [text, setText] = useState(""); const [text, setText] = useState("");

60
src/reducers.ts 100644
View File

@ -0,0 +1,60 @@
import { TodoItem } from "./types";
interface TodoState {
todos: TodoItem[];
}
const initialState: TodoState = {
todos: [],
}
export const ADD_TODO = "ADD_TODO";
export const TOGGLE_TODO = "TOGGLE_TODO";
export const DELETE_TODO = "DELETE_TODO";
interface AddTodoAction {
type: typeof ADD_TODO;
payload: TodoItem;
}
interface ToggleTodoAction {
type: typeof TOGGLE_TODO;
payload: number;
}
interface DeleteTodoAction {
type: typeof DELETE_TODO;
payload: number;
}
type TodoActionTypes = AddTodoAction | ToggleTodoAction | DeleteTodoAction;
export function todoReducer(
state = initialState,
action: TodoActionTypes
): TodoState {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case TOGGLE_TODO:
return {
...state,
todos: state.todos.map((todo) => {
if (todo.id === action.payload) {
return { ...todo, completed: !todo.completed };
}
return todo;
}),
};
case DELETE_TODO:
return {
...state,
todos: state.todos.filter((todo) => todo.id !== action.payload),
};
default:
return state;
}
}

View File

@ -1,65 +1,5 @@
import { createStore } from "redux"; import { createStore } from "redux";
import { TodoItem } from "./types"; import { todoReducer } from "./reducers";
import {stat} from "fs";
interface TodoState {
todos: TodoItem[];
}
const initialState: TodoState = {
todos: [],
}
export const ADD_TODO = "ADD_TODO";
export const TOGGLE_TODO = "TOGGLE_TODO";
export const DELETE_TODO = "DELETE_TODO";
interface AddTodoAction {
type: typeof ADD_TODO;
payload: TodoItem;
}
interface ToggleTodoAction {
type: typeof TOGGLE_TODO;
payload: number;
}
interface DeleteTodoAction {
type: typeof DELETE_TODO;
payload: number;
}
type TodoActionTypes = AddTodoAction | ToggleTodoAction | DeleteTodoAction;
export function todoReducer(
state = initialState,
action: TodoActionTypes
): TodoState {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case TOGGLE_TODO:
return {
...state,
todos: state.todos.map((todo) => {
if (todo.id === action.payload) {
return { ...todo, completed: !todo.completed };
}
return todo;
}),
};
case DELETE_TODO:
return {
...state,
todos: state.todos.filter((todo) => todo.id !== action.payload),
};
default:
return state;
}
}
export const store = createStore(todoReducer); export const store = createStore(todoReducer);