Edit todo from list in React
I don't know why I can't make it work but I just want to edit the todo from the list and save it onBlur
(when I press outside the box). I've made this work before but I think I got brain freeze or something. I deleted my attempts so the functions are empty now. Can someone nudge me in the right direction or just fill in the blanks? Thank you
UPDATE: so I want to press the todo that I've added to the list (the textinput) and then EDIT the already present todo, THEN save it to the list again!
const TEST = () => {
const [todo, setTodo] = useState("")
const [todoList, setTodoList] = useState([])
const onChangeHandler = (text) =>{
setTodo(text)
}
const saveTodo = () =>{
setTodoList([...todoList , {title: todo, key:`${Math.random()}`}])
setTodo("")
}
const onChangeTodo = () =>{
//UPDATE HERE
}
const saveonChangeTodo = () =>{
//SAVE HERE
}
return(
<View style={{flex:1, backgroundColor: "beige", justifyContent: "center", alignItems: "center", paddingTop: 300,}}>
<TextInput
placeholder="Write todo here"
style={{backgroundColor:"white", padding: 20, width: 300,}}
value={todo}
onChangeText={text=>onChangeHandler(text)}
onBlur={saveTodo}
/>
<FlatList
data={todoList}
renderItem={({item}) => {
return(<TextInput style={{borderColor: "black", borderWidth: 2, width: 200, padding: 20, margin: 10}}
value={item.title}
onChangeText={text=>onChangeTodo(text, item)}
onBlur={saveonChangeTodo}
/>
)
}}/>
Solution 1:
Change your onChangeTodo
as below. No need to have saveonChangeTodo
as it is already supported by onChangeTodo
.
const onChangeTodo = (text, item) => {
setTodoList((todos) =>
todos.map((todo) =>
todo.key === item.key ? { ...todo, title: text } : todo
)
);
};
Code Sandbox