export const ADD_TODO = 'add' export const COMPLETE_TODO = 'complete'
import { ADD_TODO, COMPLETE_TODO } from './todosActions' function getNextId(todos) { // find out id for last items and add 1 to it if (todos.length === 0) return 1; return todos[todos.length - 1].id + 1 } export default function todoReducer(state = { todos: [{ id: 1, text: "Decide what to do" }] }, action) { switch (action.type) { case ADD_TODO: let nextId = getNextId(state.todos) // get next id for todo let todo = { id: nextId, text: action.text } // create a new todo with given text return { todos: [...state.todos, { ...todo }] } // return new state after adding todo case COMPLETE_TODO: // remove todo with the given id let newTodos = state.todos.filter(t => t.id !== action.id) return { todos: [...newTodos] } default: return state; } }
import { configureStore } from '@reduxjs/toolkit' import todosReducer from './todosReducer' export default function getStore() { return configureStore( { reducer: todosReducer } ) }
import React from 'react' import { useDispatch } from 'react-redux'; import { useState } from 'react'; export default function AddTodo() { let [todoText, setTodoText] = useState('') let dispatch = useDispatch() function addTodo(e) { e.preventDefault(); dispatch({ type: 'add', text: todoText } ) // dispatch action to reducer setTodoText("") } return ( <form onSubmit={addTodo}> Todo : <input type="text" value={todoText} required onChange={(e) => setTodoText(e.target.value)} /> <input type="submit" value="Add" /> </form> ) }
import React from 'react' import {useDispatch, useSelector} from 'react-redux'; export default function ListTodos() { let todos = useSelector(state => state.todos) // get state from store let dispatch = useDispatch() function completeTodo(todoId) { dispatch({ type: 'complete', id: todoId }) // send id as payLoad } return ( <ul> {todos.map((todo) => <li key={todo.id}> {todo.text} <button className="btn btn-link" onClick={() => completeTodo(todo.id)}>Done</button> </li>)} </ul> ) }
import ListTodos from './ListTodos'; import AddTodo from './AddTodo'; export default function Todos() { return ( <> <h1>Todos</h1> <AddTodo /> <p></p> <ListTodos /> </> ) }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Todos from './Todos' import getStore from './store' import { Provider } from 'react-redux' const store = getStore() ReactDOM.render( <Provider store={store}> <Todos /> </Provider>, document.getElementById('root') );