skip to Main Content

I’m expecting to delete a task in a App.js array by filtering. But the array keeps the same after clicking the delete button in the Task child component. Even though I’m passing an id as a function attribute.

// App.js component

function App() {
  const [tasks, setTasks] = useState(Tasks);

  const deleteTask = (id) => {
    Tasks.filter((task) => task.id === id);
  };
  
  return (

<TaskComponent
  Tasks={tasks}
  changeTask={changeTask}
  deleteTask={deleteTask}
/>
)

// TaskComponent

type Tasks = {
  id: string;
  title: string;
  author_name: string;
  description: string;
  status: number | any;
  priority: number | any;
};

type Props = {
  Tasks: Tasks[];
  changeTask: (tasks: Tasks) => {};
  deleteTask: (tasks: Tasks) => {};
};

const TaskComponent: FC<Props> = ({ Tasks, changeTask, deleteTask }) => {
  const history = useHistory();

  const { id } = useParams<IdParams>();

  const task = Tasks.find((task) => String(task.id) === id);

  const [status, setStatus] = useState(task?.status);
  const [priority, setPriority] = useState(task?.priority);


  const handleDeleteTask = () => {
    deleteTask({
      ...task,
      id
    });

    history.push("/taskslist");
  };
  
  return (
  <form>
    <input type="button" value="delete" onClick={handleDeleteTask} />
  </form>
  )

CodeSandbox

3

Answers


  1. It looks like you need to use the setter method setTasks in order to set the tasks prop on your app like this:

    const deleteTask = (id) => {
       setTasks(tasks.filter((task) => task.id === id))
     };
    
    Login or Signup to reply.
    1. Tasks prop in TaskComponent should be camelCase
    2. TaskComponent – no need to include Component in the name
    3. handleDeleteTask correct naming, but what does it do? Call the callback called deleteTask… then… do something with history – not deletion related.

    So… what is deleteTask? Do you need to update a state above TaskComponent with a new Tasks value for TaskComponent i.e. a selection of tasks which does not include this task in question.

    So your issue lies in this:

    const deleteTask = (id) => {
      Tasks.filter((task) => task.id === id);
    };
    

    Does filter delete a task? No – ok so maybe you need to map / reduce / filter to create a new reference object without the task you want to delete and update the state in the parent i.e. use setTasks

    const deleteTask = (id) => {
       setTasks(tasks.filter((task) => task.id === id))
     };
    
    
    Login or Signup to reply.
  2. Problem :- you filter directly Task List that the problem page is not re-render..

     const deleteTask = (id) => {
        Tasks.filter((task) => task.id === id);
     };
    

    Solution :-

    const deleteTask = (id) => {
        let newtask = task.filter((task) => task.id !== id);
         setTasks([...newtask]);
     };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search