So I have this to-do list app and I'm working on editing the name of to-do.
When I click on button edit I get the value of the name in input field, and when I type something in that field and press enter, it should change/update to-dos' name, but right now it is only adding new to-do.
Here is code I have so far that is working, I deleted all the unsuccessful attempts. I have no more ideas.
import React, { useRef, useReducer } from 'react'
function App() {
const inputRef = useRef<HTMLInputElement | any>(null)
const handleSubmit = (e: any) => {
e.preventDefault()
inputRef.current?.value !== "" && dispatch({ type: 'ADD_TODO', payload: inputRef.current?.value })
inputRef.current && (inputRef.current.value = "")
}
const [todo, dispatch] = useReducer((state: any, action: any): any => {
switch (action.type) {
case 'ADD_TODO':
return [...state, { id: state.length, name: action.payload, isCheck: false }]
case 'CHECK_TODO':
return state.filter((item: any, index: any): any => {
if (index === action.id) {
item.isCheck = !item.isCheck
}
return item
})
case 'DELETE_TODO':
return state.filter((item: any, index: any) => index !== action.id)
case 'EDIT_TODO':
inputRef.current.focus()
inputRef.current.value = action.payload
return state
}
}, [])
const todos = todo.map((item: any, index: number) => {
return (
<li key={index}>
<input type="checkbox" checked={item.isCheck} onChange={() => dispatch({ type: "CHECK_TODO", id: index })} />
{item.name}
<button onClick={() => dispatch({ type: 'EDIT_TODO', id: index, payload: item.name })}>edit</button>
<button onClick={() => dispatch({ type: "DELETE_TODO", id: index })}>x</button>
</li>
)
})
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder='Buy milk'
ref={inputRef}
/>
</form>
<ul>{todos}</ul>
</div>
)
}
export default App
EDIT
Also, new button can be added for submit editing instead of pressing enter, as an option.