switchEtat.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export const switchEtat = (selector) => {
  2. const buttons = document.querySelectorAll(selector);
  3. /** @type (Element) */
  4. for (const button of buttons) {
  5. button.addEventListener("click", (event) => {
  6. event.preventDefault();
  7. reqSwitch(button);
  8. })
  9. }
  10. function reqSwitch(button) {
  11. const icone = button.querySelector('i');
  12. const id = button.dataset.content;
  13. const state1 = button.dataset.iconeActif;
  14. const state2 = button.dataset.iconeInactif;
  15. const path = button.dataset.path;
  16. const req = fetch(
  17. path, {
  18. method: "PATCH",
  19. body: JSON.stringify({"id_film": id})
  20. }
  21. );
  22. req
  23. .then((response) => {
  24. if (!response.ok) {
  25. throw new Error(`Erreur Http ${response.status}`);
  26. }
  27. return response.json();
  28. })
  29. .then((json) => {
  30. if (icone.className === state1) {
  31. icone.className = state2;
  32. } else {
  33. icone.className = state1;
  34. }
  35. })
  36. }
  37. }