• Latest
  • Trending
Intro to Lit: A JavaScript framework

Intro to Lit: A JavaScript framework

March 24, 2022
Do ‘bouncing universes’ have a beginning? Some cosmological models propose that the universe expands and contracts in infinite cycles, but new research finds a crucial flaw in the latest version of this theory — ScienceDaily

Do ‘bouncing universes’ have a beginning? Some cosmological models propose that the universe expands and contracts in infinite cycles, but new research finds a crucial flaw in the latest version of this theory — ScienceDaily

August 9, 2022
XNX 110V Electric Hair Cap,Hair Care Hat,Home Hair SPA Beauty Cap,Hair Steamer Thermal Heat Cap,Nourishing Hair Hat with 3 Mode Temperature Control Black

XNX 110V Electric Hair Cap,Hair Care Hat,Home Hair SPA Beauty Cap,Hair Steamer Thermal Heat Cap,Nourishing Hair Hat with 3 Mode Temperature Control Black

August 9, 2022
These “Other Duties” As Assigned From Teachers Are Bonkers

These “Other Duties” As Assigned From Teachers Are Bonkers

August 9, 2022
4 Things To Consider When Choosing A Family Dentist

4 Things To Consider When Choosing A Family Dentist

August 9, 2022
Nigeria’s dire fiscal state to worsen without subsidy removal – Budget Office

Nigeria’s dire fiscal state to worsen without subsidy removal – Budget Office

August 9, 2022
The Conservatives deserve little sympathy for their defeat on tax credits

The Conservatives deserve little sympathy for their defeat on tax credits

August 9, 2022
Serena Williams is retiring from tennis—and growing her business empir

Serena Williams is retiring from tennis—and growing her business empir

August 9, 2022
Barcelona allege Frenkie de Jong’s contract has irregularities

Barcelona allege Frenkie de Jong’s contract has irregularities

August 9, 2022
Is cloud computing immune from economic downturns?

Is cloud computing immune from economic downturns?

August 9, 2022
Woke USA Today Gives Unfunny Lecture on Modern Comedy

Woke USA Today Gives Unfunny Lecture on Modern Comedy

August 9, 2022
New research using stable isotopes sheds light on how New Zealand’s diverse range of toothed whales and dolphins coexist

New research using stable isotopes sheds light on how New Zealand’s diverse range of toothed whales and dolphins coexist

August 9, 2022
1080P HD Hidden Camera Glasses – Mini Wearable Video Recorder with 16GB Memory Card Built-in

1080P HD Hidden Camera Glasses – Mini Wearable Video Recorder with 16GB Memory Card Built-in

August 9, 2022
Dagoldinfo
Tuesday, August 9, 2022
Contact Us
Advertise
  • Home
  • World News
    The Conservatives deserve little sympathy for their defeat on tax credits

    The Conservatives deserve little sympathy for their defeat on tax credits

    What’s behind Iraq’s explosive political crisis?

    What’s behind Iraq’s explosive political crisis?

    Taiwan says multiple Chinese aircraft and vessels spotted in possible simulated attack

    Taiwan says multiple Chinese aircraft and vessels spotted in possible simulated attack

    Top Russian hypersonic missile scientist arrested on treason charge

    Top Russian hypersonic missile scientist arrested on treason charge

    Viktor Bout: The Russian arms dealer touted for US prisoner swap

    Viktor Bout: The Russian arms dealer touted for US prisoner swap

    Skin-whitening products find another largely unregulated marketplace on social media

    Skin-whitening products find another largely unregulated marketplace on social media

    Paysend introduces 50 new receiving countries to its global payments network

    Paysend introduces 50 new receiving countries to its global payments network

    Dems tout Senate passage of Inflation Reduction Act

    Dems tout Senate passage of Inflation Reduction Act

    Banks leading GOP meeting with Trump in New Jersey day after raid

    Banks leading GOP meeting with Trump in New Jersey day after raid

  • Nigerian news
    Nigeria’s dire fiscal state to worsen without subsidy removal – Budget Office

    Nigeria’s dire fiscal state to worsen without subsidy removal – Budget Office

    Oko Poly wins Cisco outstanding award on ICT – The Sun Nigeria

    Oko Poly wins Cisco outstanding award on ICT – The Sun Nigeria

    Yinka Olatunbosun dumps APC, joins Labour Party – THE AUTHORITY NEWS

    Yinka Olatunbosun dumps APC, joins Labour Party – THE AUTHORITY NEWS

    NYSC to deploy ICT tools for corps members’ supervision

    NYSC to deploy ICT tools for corps members’ supervision

    Protect NBA’s integrity, outgoing President tells lawyers

    Protect NBA’s integrity, outgoing President tells lawyers

    Females prone to engage in trafficking for prostitution — NBS | The Guardian Nigeria News

    Females prone to engage in trafficking for prostitution — NBS | The Guardian Nigeria News

    Oyo Govt. Urges Nigerians To Explore Internal Tourism

    Oyo Govt. Urges Nigerians To Explore Internal Tourism

    NEDC Commences Training for 30 Scavengers – THISDAYLIVE

    NEDC Commences Training for 30 Scavengers – THISDAYLIVE

    Bringing affordable, quality and accessible healthcare to the people of Edo State – Nigerian Observer

    Bringing affordable, quality and accessible healthcare to the people of Edo State – Nigerian Observer

  • Business
    The Conservatives deserve little sympathy for their defeat on tax credits

    The Conservatives deserve little sympathy for their defeat on tax credits

    What’s behind Iraq’s explosive political crisis?

    What’s behind Iraq’s explosive political crisis?

    Taiwan says multiple Chinese aircraft and vessels spotted in possible simulated attack

    Taiwan says multiple Chinese aircraft and vessels spotted in possible simulated attack

    Top Russian hypersonic missile scientist arrested on treason charge

    Top Russian hypersonic missile scientist arrested on treason charge

    Viktor Bout: The Russian arms dealer touted for US prisoner swap

    Viktor Bout: The Russian arms dealer touted for US prisoner swap

    Skin-whitening products find another largely unregulated marketplace on social media

    Skin-whitening products find another largely unregulated marketplace on social media

    Paysend introduces 50 new receiving countries to its global payments network

    Paysend introduces 50 new receiving countries to its global payments network

    Dems tout Senate passage of Inflation Reduction Act

    Dems tout Senate passage of Inflation Reduction Act

    Banks leading GOP meeting with Trump in New Jersey day after raid

    Banks leading GOP meeting with Trump in New Jersey day after raid

  • Entertainment
    Woke USA Today Gives Unfunny Lecture on Modern Comedy

    Woke USA Today Gives Unfunny Lecture on Modern Comedy

    ‘The Marvel Years’ Director Fred Savage Was “Manipulative and Erratic,” Based on Accusers

    ‘The Marvel Years’ Director Fred Savage Was “Manipulative and Erratic,” Based on Accusers

    NY Film Festival Selects ‘The Inspection’ as Closing Night Screening

    NY Film Festival Selects ‘The Inspection’ as Closing Night Screening

    Official US Trailer for Ruben Östlund’s Hilarious ‘Triangle of Sadness’

    Official US Trailer for Ruben Östlund’s Hilarious ‘Triangle of Sadness’

    From ‘First Man’ to 007

    From ‘First Man’ to 007

    Horror comedy Hank Boyd Is Dead

    Horror comedy Hank Boyd Is Dead

    Lady Gaga Speaks Out on Same-Sex Marriage and Abortion Rights During D.C Concert

    Lady Gaga Speaks Out on Same-Sex Marriage and Abortion Rights During D.C Concert

    Renée Zellweger Criticizes Inferior Anti-Aging Goods. I Was Eager To Turn 50

    Renée Zellweger Criticizes Inferior Anti-Aging Goods. I Was Eager To Turn 50

    Love And Thunder’ Sequence Was Added During Reshoots

    Love And Thunder’ Sequence Was Added During Reshoots

  • Science
    Do ‘bouncing universes’ have a beginning? Some cosmological models propose that the universe expands and contracts in infinite cycles, but new research finds a crucial flaw in the latest version of this theory — ScienceDaily

    Do ‘bouncing universes’ have a beginning? Some cosmological models propose that the universe expands and contracts in infinite cycles, but new research finds a crucial flaw in the latest version of this theory — ScienceDaily

    New research using stable isotopes sheds light on how New Zealand’s diverse range of toothed whales and dolphins coexist

    New research using stable isotopes sheds light on how New Zealand’s diverse range of toothed whales and dolphins coexist

    STEVE appears over Canada during ‘surprise’ solar storm

    STEVE appears over Canada during ‘surprise’ solar storm

    5 mind-bending numbers that could reveal the secrets of the universe

    5 mind-bending numbers that could reveal the secrets of the universe

    Senator who helped save Hubble donates space telescope collection

    Senator who helped save Hubble donates space telescope collection

    What Legalizing Marijuana Does to Synthetic Poisoning Cases

    What Legalizing Marijuana Does to Synthetic Poisoning Cases

    Molecular, cellular, and developmental foundations of grass diversity | Science

    Molecular, cellular, and developmental foundations of grass diversity | Science

    Good bugs, bad bugs – preserving and fermenting food in glass National Science Week 13 to 21 August

    Good bugs, bad bugs – preserving and fermenting food in glass National Science Week 13 to 21 August

    Spatial Scale Shapes the Ocean and Atmosphere’s Influence on the Climate

    Spatial Scale Shapes the Ocean and Atmosphere’s Influence on the Climate

  • Technology
    Is cloud computing immune from economic downturns?

    Is cloud computing immune from economic downturns?

    Pokemon GO August Community Day dates, locations in India revealed: Check details

    Pokemon GO August Community Day dates, locations in India revealed: Check details

    Why devops needs a better approach to cloud networking

    Why devops needs a better approach to cloud networking

    Wondering how to change font size on your iPhone? Follow these steps

    Wondering how to change font size on your iPhone? Follow these steps

    How to become a cloud architect

    How to become a cloud architect

    Midwest universities unite to support US chip industry • The Register

    Midwest universities unite to support US chip industry • The Register

    How to View, Edit and Delete Saved Passwords in Firefox

    How to View, Edit and Delete Saved Passwords in Firefox

    WhatsApp now lets you delete messages after 2 days

    WhatsApp now lets you delete messages after 2 days

    How to Manage Duplicate Photos on Windows 10

    How to Manage Duplicate Photos on Windows 10

  • Lifestyle
    4 Things To Consider When Choosing A Family Dentist

    4 Things To Consider When Choosing A Family Dentist

    ResMed acquires insomnia digital health solution somnio

    ResMed acquires insomnia digital health solution somnio

    Fatigue, headache most common long COVID symptoms

    Fatigue, headache most common long COVID symptoms

    Turning Away From Vaping, Nicotine-Addicted Teens Choose Candy, Gums

    Turning Away From Vaping, Nicotine-Addicted Teens Choose Candy, Gums

    Amwell CEO shares his thoughts on Amazon

    Amwell CEO shares his thoughts on Amazon

    Can your child hear the teacher?

    Can your child hear the teacher?

    Scientists explore ex utero generation of post-gastrulation synthetic embryos

    Scientists explore ex utero generation of post-gastrulation synthetic embryos

    Keeping Your Laundry Free From Monkeypox

    Keeping Your Laundry Free From Monkeypox

    Here’s Why Violent Video Games Are So Popular, According To A Study

    Here’s Why Violent Video Games Are So Popular, According To A Study

  • Education
    These “Other Duties” As Assigned From Teachers Are Bonkers

    These “Other Duties” As Assigned From Teachers Are Bonkers

    School pupils’ pass rates fall in Scotland for Highers and National 5s | Secondary schools

    School pupils’ pass rates fall in Scotland for Highers and National 5s | Secondary schools

    Parent-coaches count at Chongfu School

    Parent-coaches count at Chongfu School

    Oasis school where pupils don’t turn up rated ‘inadequate’

    Oasis school where pupils don’t turn up rated ‘inadequate’

    A Half Century of Student Progress Nationwide

    A Half Century of Student Progress Nationwide

    Traffickers promising university places to lure Nigerian women to Cyprus

    Traffickers promising university places to lure Nigerian women to Cyprus

    Due to CUET, Delhi University’s UG 2022 admissions process likely to be delayed: Officials

    Due to CUET, Delhi University’s UG 2022 admissions process likely to be delayed: Officials

    Social and emotional learning may be the latest buzzword, but it’s really just good teaching

    Social and emotional learning may be the latest buzzword, but it’s really just good teaching

    Chief online officers predict shift to hybrid education by 2025, survey finds

    Chief online officers predict shift to hybrid education by 2025, survey finds

  • Sport
    Barcelona allege Frenkie de Jong’s contract has irregularities

    Barcelona allege Frenkie de Jong’s contract has irregularities

    Germany striker Timo Werner returns to RB Leipzig from Chelsea | Football News

    Germany striker Timo Werner returns to RB Leipzig from Chelsea | Football News

    Serena Williams announces she will ‘evolve away from tennis’ after upcoming US Open

    Serena Williams announces she will ‘evolve away from tennis’ after upcoming US Open

    Big Ten nears media rights agreement with Fox, CBS, NBC

    Big Ten nears media rights agreement with Fox, CBS, NBC

    Liverpool’s Thiago Alcantara out for at least six weeks

    Liverpool’s Thiago Alcantara out for at least six weeks

    Kim Joo-hyung: South Korean, 20, soars to historic first PGA Tour win

    Kim Joo-hyung: South Korean, 20, soars to historic first PGA Tour win

    Real Madrid’s summer of continuity has been refreshing as rivals reboot, but will it help them stay on top?

    Real Madrid’s summer of continuity has been refreshing as rivals reboot, but will it help them stay on top?

    Mercedes driver George Russell speaks to CNN ahead of the 2022 British Grand Prix

    Mercedes driver George Russell speaks to CNN ahead of the 2022 British Grand Prix

    Patriots WR Tyquan Thornton jukes CB out of shoes at practice

    Patriots WR Tyquan Thornton jukes CB out of shoes at practice

  • Product
    XNX 110V Electric Hair Cap,Hair Care Hat,Home Hair SPA Beauty Cap,Hair Steamer Thermal Heat Cap,Nourishing Hair Hat with 3 Mode Temperature Control Black

    XNX 110V Electric Hair Cap,Hair Care Hat,Home Hair SPA Beauty Cap,Hair Steamer Thermal Heat Cap,Nourishing Hair Hat with 3 Mode Temperature Control Black

    1080P HD Hidden Camera Glasses – Mini Wearable Video Recorder with 16GB Memory Card Built-in

    1080P HD Hidden Camera Glasses – Mini Wearable Video Recorder with 16GB Memory Card Built-in

    APP Remote Control Security Camera, WiFi Camera, Hotspot Monitoring Loop Recording for Home Store Monitoring

    APP Remote Control Security Camera, WiFi Camera, Hotspot Monitoring Loop Recording for Home Store Monitoring

    Yesesion Plastic Cable Storage Box with Adjustment Compartments, Cord Organizer Case with Lid and 10 Wire Ties for Drawer, Office, Desk Accessories, Art Supply, Electronic Management (Green)

    Yesesion Plastic Cable Storage Box with Adjustment Compartments, Cord Organizer Case with Lid and 10 Wire Ties for Drawer, Office, Desk Accessories, Art Supply, Electronic Management (Green)

    Bluetooth Receiver, Bluetooth Audio Adapter for Home Stereo,Speaker, TV, Tablet, with AUX3.5/RCA Output, Low Latency and HD Audio, Dual Device Connection

    Bluetooth Receiver, Bluetooth Audio Adapter for Home Stereo,Speaker, TV, Tablet, with AUX3.5/RCA Output, Low Latency and HD Audio, Dual Device Connection

    Motospeed Professional Gaming Mechanical Keyboard RGB Led Backlit Wired with Anti-Dust Proof Switches for Gaming Keyboard for Mac & PC (Pink, 87 Key Red Switches)

    Motospeed Professional Gaming Mechanical Keyboard RGB Led Backlit Wired with Anti-Dust Proof Switches for Gaming Keyboard for Mac & PC (Pink, 87 Key Red Switches)

    Dell 3040 PC Desktop Computer, i5-6500, 16GB RAM, 480GB SSD, New 24” Monitor,1080p Webcam, New Wireless Keyboard & Mouse, 16GB Flash Drive, Wi-Fi, 4 in 1 USB HUB Win 11 Pro (Renewed)

    Dell 3040 PC Desktop Computer, i5-6500, 16GB RAM, 480GB SSD, New 24” Monitor,1080p Webcam, New Wireless Keyboard & Mouse, 16GB Flash Drive, Wi-Fi, 4 in 1 USB HUB Win 11 Pro (Renewed)

    CARFIB for Mazda 3 Accessories Car Phone Holder Mount Magnetic Magnet 2018 2017 2016 2015 2014 Cell Phone Air Vent Dedicated Navigation Black

    CARFIB for Mazda 3 Accessories Car Phone Holder Mount Magnetic Magnet 2018 2017 2016 2015 2014 Cell Phone Air Vent Dedicated Navigation Black

    Unlocked Smartphone, Rino4 Pro Android Cell Phones Unlocked, 6.1in Full Screen, 1GB RAM 8GB ROM, 2200mAh Battery, 128GB Extension, Dual SIM, Face ID & Finger Reader, Global Version(Green)

    Unlocked Smartphone, Rino4 Pro Android Cell Phones Unlocked, 6.1in Full Screen, 1GB RAM 8GB ROM, 2200mAh Battery, 128GB Extension, Dual SIM, Face ID & Finger Reader, Global Version(Green)

No Result
View All Result
Dagoldinfo
No Result
View All Result

Intro to Lit: A JavaScript framework

by dagoldtech
March 24, 2022
in Technology
0 0
0


Lit is one of the more interesting front-end JavaScript frameworks for reactive programming. It’s caught quite a bit of interest from developers, but remains relatively under the radar compared to other reactive frameworks. Lit is built on top of the Web Components standard and prioritizes speed and a small set of useful features.

Building web components with Lit

There are several ways to get started with a Lit project. For this tutorial, we’ll use a starter template. You’ll need a command line with Git and Node.js (npm) installed.

Note: Because it is based on Web Components, Lit uses the Shadow DOM to achieve reactivity.

Go to the command line and type git clone https://github.com/lit/lit-element-starter-js.git. This command deploys a simple example project into the lit-element-starter-js directory. cd into that directory and install the dependencies with npm install.

Now, you can run the application with npm run serve. If you visit localhost:8000, you’ll see the application running with the screen shown in Figure 1. (Clicking the Count button increases the count.)

Screenshot of the Hello World screen.IDG

Figure 1. The Lit starter app

Reactivity in the Lit framework

Next, let’s look at how Lit is laid out and how it achieves reactivity.

The main work happens in /dev/index.html, as shown in Listing 1.

Listing 1. Reactivity in Lit

<html>
 <head>
   <meta charset="utf-8" />
   <title>&lt;my-element> Demo</title>
   <script src="https://www.infoworld.com/article/3654302/node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
   <script src="../node_modules/lit/polyfill-support.js"></script>
   <script type="module" src="../my-element.js"></script>
   <style>
     p {
       border: solid 1px blue;
       padding: 8px;
     }
   </style>
 </head>
 <body>
   <my-element>
     <p>This is child content</p>
   </my-element>
 </body>
</html>

The main thing to note is that the page imports a Polyfill library to ensure the browser will understand Web Components. It also imports a library to assist with loading Web Components via npm. Finally, it imports a custom module, my-element.js, from the parent directory.

Next, take a look at my-element.js in Listing 2, which contains all the fundamental elements of a lit component.

Listing 2. Elements of a Lit-based component

import {LitElement, html, css} from 'lit';
/**
* An example element.
*
* @fires count-changed - Indicates when the count changes
* @slot - This element has a slot
* @csspart button - The button
*/
export class MyElement extends LitElement {
 static get styles() {
   return css`
     :host {
       display: block;
       border: solid 1px gray;
       padding: 16px;
       max-width: 800px;
     }
   `;
 }
 static get properties() {
   return {
     /**
      * The name to say "Hello" to.
      * @type {string}
      */
     name: {type: String},
     /**
      * The number of times the button has been clicked.
      * @type {number}
      */
     count: {type: Number},
   };
 }
 constructor() {
   super();
   this.name="World";
   this.count = 0;
 }
 
 render() {
   return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <slot></slot>
   `;
 }
 _onClick() {
   this.count++;
   this.dispatchEvent(new CustomEvent('count-changed'));
 }
 /**
  * Formats a greeting
  * @param name {string} The name to say "Hello" to
  * @returns {string} A greeting directed at `name`
  */
 sayHello(name) {
   return `Hello, ${name}`;
 }
}
window.customElements.define('my-element', MyElement);

The first thing to note is that lit extends the LitElement base class. You might also observe that the styles() and properties() methods are both static getter methods. We don’t have to worry about the signatures; we just use them to define the characteristics of our components.

YOU MAY ALSO LIKE

Is cloud computing immune from economic downturns?

Pokemon GO August Community Day dates, locations in India revealed: Check details

The styles() method returns the CSS for the component, and properties() returns the properties. styles() uses the css method from Lit to define component-scoped CSS in a template literal. properties() exposes the component’s reactive variables: name and count. In each case, the object returned defines the variable type in the property (for example, name: {type: “String”}).

Property values

Notice that the properties are given default values in the constructor. These are public properties, so you could comment out the name definition, for instance, and then in /dev/index.html, give the name property a value via its parent, as shown in Listing 3.

Listing 3. Public property value

<body>
   <my-element name="Galadriel">
     <p>This is child content</p>
   </my-element>
 </body>

The pattern in Listing 3 is common among reactive frameworks, allowing for the one-way, downward flow of state from parent to child.

Rendering the component

Next up is the render method, which returns view markup via the html() method and a template literal. The syntax used in the literal string is tagged literals. Notice that this method has full access to both of the properties we saw earlier (name and count), as well as methods defined on the component object, which are defined next.

Built in and custom methods

Lit has two kinds of methods: built-in and custom. The _onClick() method is built in, meaning it has special meaning for the framework. When Lit sees this method, it defines the onclick handler for the given component. In this case, it simply increments the count variable.

The second method is sayHello(name), which is a custom method called from within the view markup. Notice that this method has full access to the variables which can be passed in as arguments:

<h1>${this.sayHello(this.name)}!</h1>

All properties and methods are accessed via the this keyword; that is, they are members of the object.

Registering the component

Finally, the component calls out to the browser to register itself as a web component.

As with other reactive frameworks, Lit encourages you to write one-way code, where the template simply reflects state changes without modifying the state or DOM directly.

Slots and child elements

The Web Components standard uses slots. In our example, you can see that the component itself defines a <slot></slot> and the parent that passes in a child element (<p>This is child content</p>) that will be put into the slot.

Show and hide elements

Lit includes a variety of useful expressions, like the ability to show and hide elements.

For example, if you wanted to show an element when the counter exceeded 5, you could use something like what’s shown in Listing 4.

Listing 4. Show and hide elements

return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <div ?hidden=${this.count<5}>Not hidden</div>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <slot></slot>
   `;

Adding functionality in Lit

Now let’s add some functionality to the example. How about displaying collections?  Take a look at Listing 5.

Listing 5. Iterating over an array in Lit

static get properties() {
   return {
     name: {type: String},
     count: {type: Number},
     hobbits: []
   };
 }
 constructor() {
   super();
   this.hobbits = ["Frodo","Sam","Merry","Pippin"];
 }
 render() {
   return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <div ?hidden=${this.count<5}>Not hidden</div>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <ul>
       ${this.hobbits.map((color) =>
         html`<li style="color: ${color}">${color}</li>`
       )}
     </ul>
     <slot></slot>
   `;
 }

Listing 5 shows how you add a hobbit property, initialize it with the four most famous hobbits, and then iterate over them using a map in the render function. You might notice that React handles this sequence very similarly. You can also extract your looping logic into a function that you call from inside the template as described here.

Making Lit API calls with until

Now let’s get a look at making a remote API call. We’ll use the Lord of the Rings API to get a list of all known hobbits. You’ll also need to grab an auth token, which is free and quick.

Lit has an until directive that lets you display alternate content while awaiting the resolution of a promise. First, add that import to the head of your my-element.js: import {until} from 'lit/directives/until.js';.

Next, add the remoteHobbits to the constructor: this.remoteHobbits = getRemoteHobbits();.

Third, add the output to the render method like so:

${until(this.remoteHobbits, html`<span>Awaiting remote hobbits...</span>`)}

Notice that here we are using until to display a loading message while we await the resolution of the promise of remoteHobbits.

Take a look at the promise definition in getRemoteHobbits(), shown in Listing 6.

Listing 6. getRemoteHobbits

const getRemoteHobbits = async () => {
 const response = await fetch("https://the-one-api.dev/v2/character?race=Hobbit",
   {
     "headers": {
       "Authorization":"Bearer <YOUR API TOKEN HERE>"
     }
   }
 );
 const json = await response.json();
 const hobbits = [];
 for (const h of json.docs){
   hobbits.push(html`<li>${(h.name)}</li>`);
 }
 return hobbits;
}

Listing 6 uses a normal fetch call to get the list of characters, filtered by race=Hobbit. Note that you need to supply your API token in the Authorization header.

Finally, you marshal the JSON response into a set of list items, and return that for insertion into the HTML template.

Now, the UI will display the collection of hobbits from the remote API.

You can find the source for this demonstration in my GitHub repository.

Copyright © 2022 IDG Communications, Inc.



Source link

ShareTweetShareSendShareShare

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Home
  • World News
  • Nigerian news
  • Business
  • Entertainment
  • Science
  • Technology
  • Lifestyle
  • Education
  • Sport
  • Product
Call us for advertisement: + 234 8111770774 Email: advertise@dagoldinfo.com.ng

© 2022 DagoldInfo

No Result
View All Result
  • Home
  • World News
  • Nigerian news
  • Business
  • Entertainment
  • Science
  • Technology
  • Lifestyle
  • Education
  • Sport
  • Product

© 2022 DagoldInfo

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In