How do I filter and delete specific objects in the database? | React as Front and Rails as Back/API

Viewed 109

So, here is the thing, I'm learning React right now, and I'm building a small taskmanager webapp with React as frontend and Rails(API) as Backend to pratice using React with Rails(which I'm already used to build other webapps with). The tasks are objects in the database which have a "title" as a string, and "done" as a boolean to indicated if they're done or not. Using async and await fetch('') I managed to create functions to be able to pass methods directly to the database to check and uncheck the tasks as done, and also delete the tasks. Like that, for example:

async deleteTask(task) {
            if (window.confirm(`Are you sure you want to delete: "${task.title}"`)) {
                await fetch(`http://localhost:3001/tasks/${task.id}`, {method: 'DELETE'});
                this.props.loadTasks();
            }
        }

Now I want to create a function to delete ALL of the done tasks at once. How would I do that? How do I take all of the tasks and filter them by "done == true" or something like that and pass a DELETE method to the database? Thanks in advance, any help is appreciated! I tried many alternatives, even tried something like that, no sucess:

async deleteAllDoneTasks() {
      if (window.confirm(`Are you sure you want to delete all done tasks?`)) {
          await fetch(`http://localhost:3001/tasks/)`, {method: 'DELETE FROM Tasks WHERE done = 1'});
          this.props.loadTasks();
      }
    }

EDIT¹: So, according to JMadelaine this can't be made by the frontend. How do I do that in Rails then? And how do I call that in React, make it happen when I press a button? I commented below what I would do first. I'd appreciate any insight, help, or solutions. Thanks :)

1 Answers

First of all you need a custom route for this action as it is not default CRUD action. So in the routes.rb under the tasks route add custom route like:

delete 'tasks', to: 'tasks#multiple_delete'

Then in TasksController define multiple_delete method with code inside which will delete desired tasks and return answer to your client, something like:

def multiple_delete
  ::Task.where(done: true).destroy_all
  head :ok
end

and then in your React, according to answer from server you can do some things.

Then go to your React code, on desired button add onClick event (I do not know which framework you use, I will share example of Shopify code which I am familiar with.
outside the render() do:

deleteAllDoneTasks = () => {
      if (window.confirm(`Are you sure you want to delete all done tasks?`)) {
          await fetch(`http://localhost:3001/tasks)`, {method: 'DELETE'})
      }
}

inside the render() do:

<Button onClick={this.deleteAllDoneTasks}>
Related