TOTAL CODE
APP.JS
import "./App.css";
import Todo from "./components/Todo";
import { Provider } from "react-redux";
import { store } from "./app/store";
function App() {
return (
<>
<Provider store={store}>
<Todo />
</Provider>
</>
);
}
export default App;
TODO.JSX
import { useSelector } from "react-redux";
import AddForm from "./AddForm";
import { useDispatch } from "react-redux";
import { deleteTodo, markAsDone } from "../Features/Todo/TodoSlice";
export default function Todo() {
const todos = useSelector((state) => state.todos);
console.log(todos);
const dispatch = useDispatch();
let Delete = (id) => {
dispatch(deleteTodo(id));
};
let Mark = (id) => {
console.log(id);
dispatch(markAsDone(id));
};
return (
<>
<h3>Todo App</h3>
<AddForm />
<ul>
{todos.map((todo) => (
<li key={todo.id} >
<span style={todo.isDone ? { textDecoration: "line-through" } : {}}>
{todo.task}
</span>
<button
onClick={() => {
Delete(todo.id);
}}
>
delete
</button>
<button
onClick={() => {
Mark(todo.id);
}}
>
Mark as Read
</button>
</li>
))}
</ul>
</>
);
}
ADDFORM.JSX
import { useState } from "react";
import { useDispatch } from "react-redux";
import { addTodo } from "../Features/Todo/TodoSlice";
export default function AddForm() {
const [task, setTask] = useState("");
const dispatch = useDispatch();
let handleChange = (event) => {
setTask(event.target.value);
};
let handleSubmit = (event) => {
event.preventDefault();
console.log(task);
dispatch(addTodo(task));
setTask("");
};
return (
<>
<form onSubmit={handleSubmit}>
<input placeholder="add task" type="text" onChange={handleChange} />
<button>submit</button>
</form>
</>
);
}
IN FEATURES, TODOSLICE.JS
import { createSlice, nanoid } from "@reduxjs/toolkit";
const initialState = {
todos: [],
};
export const todoSlice = createSlice({
name: "todo",
initialState,
reducers: {
addTodo: (state, action) => {
const newTodo = {
id: nanoid(),
task: action.payload,
isDone: false,
};
state.todos.push(newTodo);
},
deleteTodo: (state, action) => {
//action.payload
state.todos = state.todos.filter((todo) => todo.id !== action.payload);
},
markAsDone: (state, action) => {
state.todos.map((todo) => {
if (todo.id === action.payload) {
todo.isDone = true;
}
});
},
},
});
export const { addTodo, deleteTodo, markAsDone } = todoSlice.actions;
export default todoSlice.reducer;
SRC/APP/STORE.JS
import { configureStore } from "@reduxjs/toolkit";
import todoReducer from "../Features/Todo/TodoSlice";
export const store = configureStore({
reducer: todoReducer,
});
Comments
Post a Comment