Created
December 20, 2022 06:27
-
-
Save popdemtech/df211ed72ccafdbe840c704092b9596c to your computer and use it in GitHub Desktop.
Web Component which makes an API call and renders the response on screen π
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
| <html> | |
| <head> | |
| <!-- This file defines a web component APICard/api-card --> | |
| <!-- which, when given an JSON returning route, --> | |
| <!-- renders the response returned by the route --> | |
| <!-- or the error message returned by the route --> | |
| <!-- in a graphical, user-friendly way --> | |
| </head> | |
| <body> | |
| <!-- Using the api-card component --> | |
| <api-card route="/api/ping"></api-card> | |
| <api-card route="/api/health"></api-card> | |
| <api-card route="https://gist.githubusercontent.com/popdemtech/83d9430bafd2b968b6b8a74ecc19734a/raw/52a4c3382db9182277403cf112303e4c4d257d93/json.json"></api-card> | |
| <script> | |
| class APICard extends HTMLElement { | |
| constructor() { | |
| super(); | |
| } | |
| async connectedCallback() { | |
| this.route = this.getAttribute('route'); | |
| await fetch(this.route).then((response) => response.json()) | |
| .then((data) => { | |
| this.response = JSON.stringify(data, null, 2); | |
| }) | |
| .catch((e) => { | |
| this.response = e.message; | |
| }); | |
| this.render(); | |
| } | |
| render() { | |
| this.innerHTML = ` | |
| <div class="api-card"> | |
| <p><b>${this.route}</b></p> | |
| <pre style="background-color:#ddd;padding:10px;width:fit-content;">${this.response}</pre> | |
| </div> | |
| <hr> | |
| `; | |
| } | |
| } | |
| customElements.define("api-card", APICard); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment