Below is a simple ToDo-List Code by using useReducer().
I am trying to toggle the check box. Although Code is working
concept wise I am not able to understand why dispatch function is being called inside an anonymous arrow function ?
import initialTodos from "./Data";
import { useReducer } from "react";
const reducer = (state, action) => {
switch (action.type) {
case "COMPLETE":
return state.map((todo) => {
if (todo.id === action.id) {
return { ...todo, complete: !todo.complete };
} else {
return todo;
}
});
default:
return state;
}
};
export default function Todos() {
const [todos, dispatch] = useReducer(reducer, initialTodos);
return (
<>
{todos.map((todo) => (
<div key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={() => dispatch({ type: "COMPLETE", id: todo.id });} // dispatch(actionObject);
/>
{todo.title}
</label>
</div>
))}
</>
);
}