Skip to content

Instantly share code, notes, and snippets.

@grodriguez1983
Created December 18, 2023 16:09
app/javascript/controllers/shopping_item_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="shopping-item"
export default class extends Controller {
connect() {
}
toggle_bought(e) {
const id = e.target.dataset.id
const shoppingListId = e.target.dataset.shopping_list_id
const csrfToken = document.querySelector("[name='csrf-token']").content
fetch(`/shopping_lists/${shoppingListId}/shopping_items/${id}/toggle_bought`, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
body: JSON.stringify({ bought: e.target.checked }),
})
.then(response => response.json())
.then(data => {
alert(data.message)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment