Home > database >  Deleting data off an array and then re-rendering updated list
Deleting data off an array and then re-rendering updated list

Time:11-17

I have a set of data that I have fetched from a third-party API site but would like to delete entries from it without using the DELETE crud method. It does work without any hiccup except for the fact that the screen doesn't render the updated list after deletion. My code is as follows:

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)
            })
    }, []);
    // console.log(`todos : ${todos}`);
    // const arr = todos;


    // console.log(arr.length);
    // console.log(`data : ${arr}`);
    // const array = arr;


    const deleteTodo = (index) => {
        const del = todos.splice(index, 1)
        // console.log(index);
        // console.log(`newData : ${arr} || newLength : ${arr.length}`);
        console.log(`newLength : ${todos.length}`);     //to check the 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 class='btn btn-danger ' onClick={() => deleteTodo(todos[value].id)}> Delete </button>
                            </td>

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

It works up to the extent of displaying the reduced length post clicking the delete button but as mentioned earlier, the list that gets rendered initially remains the same no matter how many times I click the delete button. For example : enter image description here

CodePudding user response:

splice is a mutating method, which means that you're directly mutating your state and that breaks the rules of React. You could just change your deleteTodo to be something that creates a new array, deletes the desired item and then sets your state using useState, e.g.:

const deleteTodo = (index) => {
   const temp = [...todos];
   temp.splice(index, 1);
   setTodos(temp);
}

Other solutions are possible (like using filter since it is a non-mutating method) but this should work just fine.

CodePudding user response:

you should return rest of the array, then splice it , and after that set it again in your state

function deleteItem(index){
 setTodos([...todos].splice(index,1))
}
  • Related