Home > database >  Index Item of array not getting deleted
Index Item of array not getting deleted

Time:11-17

I've just noticed a problem with my UI where clicking the delete button at a particular index doesn't delete that particular record and instead ends up deleting data situated at a different index. I'm quite clueless as to why this is happening. The list seems to render properly in order but then it all goes south when I try deleting it. My first deduction of this issue for a split second was that this had something to do with the API that I'm fetching the data from but then I realized that the data was getting rendered as it should and as it was defined. I would like to know what I can do to ensure that I'm deleting the data that I've clicked and not anything else. Here is my code:

import { useEffect, useState } from "react";

const Task = () => {
    const [todos, setTodos] = useState([]);


    useEffect(() => {
        fetch('http://jsonplaceholder.typicode.com/todos')
            .then(res => res.json())
            .then(data => {
                setTodos(data)
            })
    }, []);

    const deleteTodo = (index) => {
        const temp = [...todos];
        temp.splice(index, 1);
        setTodos(temp);
        console.log(index);
        // console.log(`newData : ${arr} || newLength : ${arr.length}`);
        console.log(`newLength : ${todos.length}`);
    }

    return (
        <div className='container'>
            <table className='table'>
                <tbody>
                    {todos.map((key, value) => (
                        <tr key={key.id}>
                            <td>{todos[value].id}</td>
                            <td>{todos[value].title}</td>
                            <td>{`${todos[value].completed}`}</td>
                            <td>
                                <button className='btn btn-danger ' onClick={() => deleteTodo(key.id)}> Delete </button>
                            </td>

                        </tr>
                    ))}
                </tbody>
            </table>
            <button className='btn btn-primary'>Add Task</button>
        </div>
    );
}
export default Task;

CodePudding user response:

You are passing key.id to deleteTodo and then delete the item in the todo with index of key.id and it may not as the same as the index of the item, you should pass the index of item to the deleteTodo

like this :

{todos.map((todoItem, todoIndex) => (
                    <tr key={todoItem.id}>
                        <td>{todoItem.id}</td>
                        <td>{todoItem.title}</td>
                        <td>{`${todoItem.completed}`}</td>
                        <td>
                            <button className='btn btn-danger ' onClick={() => deleteTodo(todoIndex)}> Delete </button>
                        </td>

                    </tr>
                ))}

CodePudding user response:

Mehtod .splice() needs index of element as start index, but you are sending an id. So, if id is 1 you will remove element on position 1, what is other element.

You can do .findIndex of element by id inside your delete function. There is working example Example

  • Related