Reputation: 13
I was making a to-do app in react-native. I made a function that deletes the task on press but when I do press, it deletes the first item on the list, not the one I pressed on. Here is the code I used:
let id = 0;
const [task, setTask] = useState("");
const [taskList, setTaskList] = useState([
{ name: "Add your first task", id: id++ },
]);
const handleTask = (e) => {
e.preventDefault();
setTaskList([...taskList, { name: task, id: id++ }]);
setTask("");
};
function completeTask(index) {
let itemsCopy = [...taskList];
itemsCopy.splice(index, 1);
setTaskList(itemsCopy);
}
{taskList.map((taskList, index) => {
return (
<View style={styles.wrapper}>
<View style={styles.text}>
<TouchableOpacity key={index} onPress={completeTask}>
<Text> {taskList.name} </Text>
</TouchableOpacity>
</View>
</View>
);
})}
Upvotes: 0
Views: 103
Reputation: 12787
You don't pass index when call completeTask
and update state wrond way.
onPress={() => completeTask(index)}
function completeTask(index) {
setTaskList((preTasks) => preTasks.filter((item, i) => i !== index));
}
Upvotes: 1