home.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. export default {
  2. rendered: false,
  3. render: function(){
  4. if(!this.rendered){
  5. this.getWorkouts();
  6. this.buttons();
  7. this.rendered = true;
  8. }
  9. },
  10. buttons: function(){
  11. document.getElementById("homeLogout").addEventListener("click", ()=>{
  12. fetch("/user/logout")
  13. .then(r=>r.json())
  14. .then((response)=>{
  15. if(response.error){
  16. notify("error", response.error.message);
  17. }else{
  18. changePage("login");
  19. }
  20. })
  21. .catch((err)=>{
  22. notify("error", "Something went wrong, try refreshing the page");
  23. });
  24. });
  25. document.getElementById("homeNewWorkout").addEventListener("click", ()=>{
  26. changePage("newWorkout");
  27. });
  28. },
  29. getWorkouts: function(){
  30. fetch("/workout", {
  31. method: "get",
  32. headers: {
  33. "Content-Type": "application/json"
  34. }
  35. })
  36. .then(r=>r.json())
  37. .then((response)=>{
  38. if(response.error){
  39. notify("error", response.error.message);
  40. }else{
  41. this.renderWorkouts(response);
  42. }
  43. })
  44. .catch((err)=>{
  45. notify("error", "ERROR: Unable to retrieve workouts");
  46. });
  47. },
  48. renderWorkouts: function(workouts){
  49. const workoutList = document.getElementById("workoutList");
  50. while(workoutList.children.length > 0){
  51. workoutList.removeChild(workoutList.firstChild);
  52. }
  53. for(let i = 0; i < workouts.length; i++){
  54. const button = document.createElement("button");
  55. button.classList.add("button");
  56. button.textContent = workouts[i].name;
  57. button.addEventListener("click", ()=>{
  58. changePage("workout", workouts[i]);
  59. });
  60. workoutList.appendChild(button);
  61. }
  62. }
  63. }