reactjsrecoiljs

How to implement delete function with recoil and react.js


I'm implementing a to-do list app using Recoil. The function to delete items is not working properly yet. Below is a part of my code.

// ToDoList.js

import React from 'react';
import { useRecoilValue, useRecoilState } from 'recoil';
import { todoListState } from './atoms';

function ToDoList() {
  const [todos, setTodos] = useRecoilState(todoListState);

  const handleDelete = (id) => {
    setTodos([])
  };

  return (
    <div>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            {todo.text}
            <button onClick={() => handleDelete(todo.id)}>DELETE</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ToDoList;


The item is not deleted correctly and the list is not updated.


Solution

  • You can modify the handleDelete function to remove the item with the specified ID from the todoListState atom. Here's an example implementation:

    import React from 'react';
    import { useRecoilValue, useRecoilState } from 'recoil';
    import { todoListState } from './atoms';
    
    function ToDoList() {
      const [todos, setTodos] = useRecoilState(todoListState);
    
      const handleDelete = (id) => {
        setTodos((prevTodos) => prevTodos.filter((todo) => todo.id !== id));
      };
    
      return (
        <div>
          <ul>
            {todos.map((todo) => (
              <li key={todo.id}>
                {todo.text}
                <button onClick={() => handleDelete(todo.id)}>DELETE</button>
              </li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default ToDoList;