Deleting a record

Linked Projects:

Calreact
 
Letā€™s add a way to delete an appointment.

InĀ ApointmentForm, add a delete button below the form.

{this.state.editing && (
  <p>
    <button onClick={this.deleteAppointment}>
      Delete Appointment
    </button>
  </p>
  )
}

which weā€™ll define underĀ addAppointment.

addAppointment () {
   const appointment = {title: this.state.title.value,
                           appt_time: this.state.appt_time.value};
  . . .
      });
    }
  
   deleteAppointment = () => {

We need to make aĀ deleteĀ request. To do that, we can use the AJAX call from ourĀ updateAppointmentĀ method and modify it.

updateAppointment () {
   const appointment = {title: this.state.title.value,
                           appt_time: this.state.appt_time.value};
   $.ajax({
        type: "PATCH",
        url: `http://localhost:3001/appointments/${this.props.match.params.id}`,
        data: {appointment: appointment},
        headers: JSON.parse(sessionStorage.getItem('user'))
      })
      .done((data) => {
   console.log('appointment updated!');
   this.resetFormErrors();
      })
      .fail((response) => {
   this.setState({formErrors: response.responseJSON,
                        formValid: false});
      });
    }

Change type to DELETE and remove theĀ data:Ā line. We only need the URL.

deleteAppointment= () => {
  $.ajax({
    type: "DELETE",
    url: `/appointments/${this.props.match.params.id}`
  })

Then, letā€™s say updateĀ .done:Ā 

deleteAppointment= () => {
  $.ajax({
    type: "DELETE",
    url: `/appointments/${this.props.match.params.id}`
  })
  .done((data => {
    console.log('appointment deleted!');
    this.resetFormErrors();
  })
  .fail((response=> {
    console.log('appointment deleting failed!');
  });
}

If the request fails, weĀ  console-log the message that appointment deletion failed:

  .done((data => {
    console.log('appointment deleted!');
    this.resetFormErrors();
  })
  .fail((response=> {
    console.log('appointment deleting failed!');
  });
}

We want to redirect the user to the homepage; letā€™s add a controller action for deleting inĀ appointments_controller.rb:Ā 

  def destroy
    @appointment = Appointment.find(params[:id])
    if @appointment.destroy
      head :no_content, status: :ok
    else
      render json: @appointment.errors, status: :unprocessable_entity
    end
  end

Now redirect the user by changing the console-log line inĀ .doneĀ (back in AppointmentForm):

.done((data => {
    this.props.history.push(ā€˜/ā€™);
    this.resetFormErrors();
  })

The route changes as you can see in the address bar, but looks like somethingā€™s broken.

[screenshot: 1:53]

The AppointmentsList component is throwing the null appointments error again.

[screenshot 2:02]

This is happening because if we look in the route definition, itā€™s expecting appointments in the props but in the redirect, weā€™re not passing anything.

We can simplify this route.

Letā€™sĀ  render the Appointments component on the route and not worry about passing appointments data in the props. This is what the export section of AppRouter.jsx will now look like:

export default(props) => {
  return (
    <Router>
      <div>
        <Route path="/" component={AppHeader} />
        <Route exact path="/" component={Appointments} />
        <Route exact path="/appointments/:id" component={Appointment} />
        <Route path="/appointments/:id/edit" component={AppointmentForm} />
      </div>
    </Router>
  )
}

So we can also remove the props from the index view.

= react_component('AppRouter')

Now the route renders the Appointments component and then fetches the data from the server.

Go to the homepage, select an appointment, click the delete button.

The appointment gets deleted and Iā€™m redirected to the homepage, which loads fine now.

So deletion works, but one thing we should add is a confirmation dialogue for the user to make sure they donā€™t delete a record by mistake.

We can wrap our AJAX call inĀ deleteAppointmentĀ in aĀ confirmĀ call. Itā€™s a JavaScript browser function whichĀ  asks the user to confirm an action in an alert box:

deleteAppointment = () => {
  if(confirm("Are you sure you want to delete this appointment?")) {
    $.ajax({
      . . .
    });
  }
)

Now, try it.Ā 

If I click the delete button I get an alert:

[screenshot 3:28]

Clicking onĀ CancelĀ dismisses the alert and nothing happens.

Clicking onĀ OK, the appointment gets deleted and I get redirected to the homepage.

That is deletion.

Liked this tutorial? Get more like this in your inbox