Norbert
Norbert

Reputation: 111

How to fetch delete in Javascript using Rails API

I'm trying to send a fetch delete request using Rails as API. Here's the destroy method in the controller.

def destroy
  track = Track.find_by(id: params[:id])
  track.destroy
end

I'm creating tracks on what would be an app to create song playlists. In index.js I'm calling the event listener in the render track card function.

const renderTrackCard = (trackObj) => {
    let trackCard = document.createElement('div')
    trackCard.className = 'card'
    trackCard.dataset.id = trackObj.id
    trackCard.innerHTML = `
      <p>${trackObj.title} - ${trackObj.artist} - Genre: ${trackObj.genre} <button class="delete-btn" data-action="delete" id="delete-btn"> X </button></p>
    `
    main().appendChild(trackCard)
    document.querySelector('div').addEventListener('click', removeTrack)
}

Followed then by the remove track function.

function removeTrack() {
    event.preventDefault()
    clearTrackForm()
    let id = event.target.dataset.id 
    fetch(BASE_URL+`/tracks/${id}`, {
        method: "DELETE",
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(event.target.parentElement.remove())
}    

When I click on the delete button, nothing happens. Please advise.

Upvotes: -1

Views: 1061

Answers (1)

Spawn
Spawn

Reputation: 58

First thing, what to you think to call destroy! instead destroy to see the StackTrace and know what are going on to your database?

And to do a request to your server-side you can use AJAX like this one

Upvotes: 0

Related Questions