Created
October 11, 2022 19:56
-
-
Save loraxx753/a4090c0de0e4693db3067689310b1c83 to your computer and use it in GitHub Desktop.
quick Web Component API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
customElements.define('the-api', class extends HTMLElement { | |
static get observedAttributes() { return ['endpoint', 'base']; } | |
async updateData() { | |
const url = this.hasAttribute('base') | |
? new URL (this.getAttribute('endpoint'), this.getAttribute('base')) | |
: new URL(this.getAttribute('endpoint')) | |
this.response = await (await fetch(url)).json() | |
// If an array, pick a random item | |
if(Array.isArray(this?.response)) { | |
this.response = this.response[Math.floor(Math.random() * this.response.length)] | |
} | |
for (const [key, value] of Object.entries(this.response)) { | |
[...document.querySelectorAll(`[api-key=${key}]`)].map(element => element.innerText = value) | |
} | |
} | |
async connectedCallback() { | |
this.updateData(this.getAttribute('endpoint')) | |
} | |
attributeChangedCallback(name, oldValue, newValue) { | |
!!oldValue ? this.updateData(newValue) : null; | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment