Username:${this.userData.username}
+Honor Points:${this.userData.honor}
+ +Completed Challenges: ${ + this.userData.codeChallenges.totalCompleted + }
+Leaderboard Rank: ${leaderboard}
+Rank:${ + this.userData.ranks.overall.name + }
+Failed to load Codewars data. Please try again later.
`; } } - customElements.define("codewars-badge", CodeWarsBadge); +/* New functionality added for the stretch exercise which is displaying the recent challenges. */ +//creating a new class that extend html element to make the class a web component +class RecentChallenges extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: "open" }); + this.userName = "Mikiyas-STP"; + this.challenges = []; // to store the fetched challenges + } +//this code detects observed attributes of the username + static get observedAttributes() { + return ["username"]; + } +//for the changed username if oldvalue is different from newvalue replace the username with the new value then fetch the challanges. + attributeChangedCallback(name, oldValue, newValue) { + if (name === "username" && oldValue !== newValue) { + this.userName = newValue; + this.fetchChallenges(); + } + } + + connectedCallback() { + this.fetchChallenges() + .then(() => this.render()) + .catch((error) => { + console.error("Error fetching recent challenges:", error); + this.renderError(); + }); + } + async fetchChallenges() { + try { + const res = await fetch( + `https://www.codewars.com/api/v1/users/${this.userName}/code-challenges/completed` + ); + if (!res.ok) throw new Error(`HTTP error! Status: ${res.status}`); + const data = await res.json(); + this.challenges = data.data.slice(0, 5); // Get the latest 5 challenges + this.render(); + } catch (error) { + console.error("Failed to fetch challenges:", error); + this.challenges = null; + this.renderError(); + } + } + render() { + if (!this.challenges) return; + + this.shadowRoot.innerHTML = ` + +Recent Challenges
+ ${this.challenges + .map( + (challenge) => ` +Name: ${challenge.name}
+Completed At: ${new Date( + challenge.completedAt + ).toLocaleDateString()}
+ +Failed to load recent challenges. Please try again later.
`; + } +} +customElements.define("codewars-recent-challenges", RecentChallenges); + diff --git a/index.html b/index.html index bbb3149..353be7c 100644 --- a/index.html +++ b/index.html @@ -3,15 +3,14 @@ -