Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import React, { useState } from 'react';

import { createStore } from 'redux';


import { Provider, useDispatch, useSelector } from 'react-redux';

const initialState = [];

const reducer = (state = initialState, action) => {


switch(action.type){
case "ADD":
return [...state, action.payload];
case "DEL":
return state.filter((_, i) => i !== action.payload);
case "EDIT":
const newArr = [...state];
newArr[action.payload.index] = action.payload.newVal;
return newArr;
default:
return state;
}
}

const store = createStore(reducer);


const TodoList = () => {
const [newTask, setNewItem] = useState('');
const tasks = useSelector(state => state);
const dispatch = useDispatch();

const handleAdd = () => {


dispatch({ type: 'ADD', payload: newTask });
setNewItem('');
};
const handleDelete = (index) => {
dispatch({ type: 'DEL', payload: index });
};
const handleEdit = (index) => {
const newVal = prompt('Enter the modification:');
dispatch({ type: 'EDIT', payload: { index, newVal } });
};

return (
<div>
<h1>Todo List:</h1>
<input type="text" placeholder="Enter your mission for today" value={newTask}
onChange={(e) => setNewItem(e.target.value)} />
<button onClick={handleAdd}>Add</button>
<div>
{tasks.map((item, index) => (
<ul key={index}>
<li>{item}</li>
<button onClick={() => handleDelete(index)}>Delete</button>
<button onClick={() => handleEdit(index)}>Edit</button>
</ul>
))}
</div>
</div>
)
}

export default function App() {


return (
<div>
<Provider store={store}>
<TodoList />
</Provider>
</div>
)
}

You might also like